How to Center a Text Inside the CSS :before Pseudo-Element

Solution with absolute positioning

In this snippet, we will try centering a text within the CSS :before pseudo-element thus making the text to be in the middle of the <span> element.

You need to position the :before pseudo-element absolutely by using the well known centering technique (use the top, left, and transform properties). Here, -25px will offset the text above the circle.

Note that for the <span> element, we set the position property to its "relative" value and the display to "block".

Example of centering a text within the :before pseudo-element:

<!DOCTYPE html>
    <title>Title of the document</title>
      span {
        border-radius: 50%;
        background-color: #c7dbc1;
        border: 4px solid #47962f;
        width: 25px;
        height: 25px;
        margin: 30px 0 0 40px;
        display: block;
        position: relative;
      span:before {
        content: attr(data-value);
        position: absolute;
        white-space: pre;
        display: inline;
        top: 0;
        left: 50%;
        transform: translate(-50%, -25px);
    <span data-value="Lorem Ipsum"></span>

Do you find this helpful?

Related articles