user2629417
user2629417

Reputation: 55

Pseudo-elements and flexboxes in CSS

I am learning CSS and I am seeing something I don't understand. I am essentially doing the following:

.flexbox {
  display: flex;
}

div.flexbox::after {
  display: block;
  content: "X";
}

.item {
  flex: 1;
  height: 200px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<div class="flexbox">
  <div class="item red"></div>
  <div class="item blue"></div>
  <div class="item green"></div>
</div>

I would have expected the "X" to appear on a new line, given that it is a block-level element. However, it is appearing inline -- at the end of the row of divs.

I am using firefox 52.7.4 for what it's worth.

Any insights would be appreciated.

Thanks

Upvotes: 4

Views: 10526

Answers (2)

AdamDenny
AdamDenny

Reputation: 52

Pseudo-elements don't exist outside the bounding boxes of the element they're appended after. If you inspect the element, you'll see the ::after appear within the <div class="flexbox"> element.

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 273530

You are using flexbox and the default behavior is nowrap. Then you should specify any width or flex-basis that make the total width of the child elements exceed the width of their container in order to have the wrap.

display:block will have no effect in this case, you need to consider the flex properties to force the line break.

Here is an example:

.flexbox {
  display: flex;
  flex-wrap:wrap;
}

div.flexbox::after {
  content: "X";
  flex-basis:100%;
}

.item {
  flex:1 0 30%;
  height: 200px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<div class="flexbox">
  <div class="item red"></div>
  <div class="item blue"></div>
  <div class="item green"></div>
</div>

Upvotes: 5

Related Questions