Fellow Stranger
Fellow Stranger

Reputation: 34113

:before gets placed above (instead of to the left) when element contains block elements

I have a pseudo element that I'd like to have placed to the left of it's pertaining element (.alpha).

But when that element contains a block element (.beta), the pseudo element gets placed above everything.

Is there a workaround for this or is it impossible to have block elements inside an element with pseudo-element?

Here's a live example.

<div class='alpha'>
  <div class='beta'>paragraph text</div>
</div>

.alpha:before {
    content: "this is ";
    font-weight: bold;
    font-style: italic;
}

Upvotes: 0

Views: 112

Answers (2)

Mohammad Usman
Mohammad Usman

Reputation: 39392

Method # 01:

Use an inline element for class .beta like span, em etc. in your code.

.alpha:before {
    content: "this is ";
    font-weight: bold;
    font-style: italic;
}
<div class='alpha'>
  <span class='beta'>paragraph text</span>
</div>

Method # 02:

Add float: left with some margin-right on your pseudo element and set its layout if you have mixture of inline and block elements inside parent.

.alpha {
    overflow: hidden;
}

.alpha:before {
    content: "this is ";
    font-weight: bold;
    font-style: italic;
    margin-right: 4px;
    float: left;
}
<div class='alpha'>
  <div class='beta'>
  paragraph text
  </div>
</div>

Upvotes: 1

RussAwesome
RussAwesome

Reputation: 464

Add

.alpha:before {
    content: "this is ";
    font-weight: bold;
    font-style: italic;
}

.beta {display:inline;}

By making the beta div no longer a block element, you achieve your desired behaviour.

https://jsfiddle.net/xs1s8Lee/1/

Upvotes: 0

Related Questions