Ben
Ben

Reputation: 16699

How to display the :after content outside element

In the following case, how can I make it such that the text generated by the :after is outside the box of the span? (It currently is rendered inside, i.e. it makes the span element wider)

HTML

<span class="my">Boxtext</span>

CSS

span.my {
    padding:            4px 8px;
    background-color:   red;
    display:            inline-block;
    border-radius:      10px;
    margin-left:        20px;
    }   
span.my:after {
    content:            " text that is supposed to come after the box";
    }

I guess this is somewhat similar to list-style-position, where you can chose inside or outside...

Upvotes: 23

Views: 19637

Answers (2)

David Thomas
David Thomas

Reputation: 253506

Just use position: absolute in the ::after {} pseudo-element's css:

span.my:after {
    content: " text that is supposed to come after the box";
    position: absolute;
    left: 100%;
}​

Remember, of course, to use position: relative; (or any other position value) on the parent span.my element.

JS Fiddle demo.

Also remember that as the ::after (and the ::before) pseudo-element inherits from the span to which it's 'attached' that it'll inherit the width, so that may need to be explicitly overridden in the CSS for that/those elements.

Upvotes: 7

Joel
Joel

Reputation: 19378

I believe CSS content is considered part of the object against which it was rendered. You could make the argument that :after should have been named :append.

For your case you can try putting an extra element inside span.my:

<span class="my"><span>Boxtext</span></span>
span.my span { ... }
span.my:after { ... }

Or styling the content specifically.

span.my:after { 
    content:            " text that is supposed to come after the box";
    background-color:   white;
    position:           absolute;
    margin-left:        10px;
}

Upvotes: 12

Related Questions