user19103974
user19103974

Reputation: 358

Flex first child 100% width without increasing the width of the container

I have a flexbox element and I want the first child to be 100% width, which is working fine, however this has led to an unintended consequence which is that the width of the flex container is still taking up the width that it would be if the first child was not 100% width.

.flex {
  display:inline-flex;
  flex-wrap:wrap;
  border:1px solid black;
}

.first-child {
  display:inline-block;
  width:100%;
  padding:10px 0;
}

.image {
  margin-left:5px;
}
.image:nth-child(2) {
  margin-left:0;
}

img {
  display:block;
}
<div class="flex">
  <span class="first-child">Lorem Ipsum</span>
  <div class="image">
    <img src="https://i.picsum.photos/id/54/300/300.jpg?hmac=LmoFB-1252dfBUuC19mSt9fePqp2CCJEY2_EL9ewdPE" />
  </div>
  <div class="image">
    <img src="https://i.picsum.photos/id/916/300/300.jpg?hmac=lP6QL2bac_8f8XYGAVNzgf2nHPlfRUNDAiDM-Kejgpg" />
</div>

I have added a border to the container to demonstrate how it is wider than I expect. How can I go about making sure the first child is on it's own line with 100% width while still having the border end right at the right side of the second image?

Current result: enter image description here

Upvotes: 0

Views: 321

Answers (1)

Temani Afif
Temani Afif

Reputation: 273004

Use CSS grid for this:

.grid {
  display: inline-grid;
  gap: 5px;
  border: 1px solid black;
}

.first-child {
  padding: 10px 0;
  grid-column: span 2; /* update this to the number of images*/
}

img {
  display: block;
}
<div class="grid">
  <span class="first-child">Lorem Ipsum</span>
  <div class="image">
    <img src="https://i.picsum.photos/id/54/300/300.jpg?hmac=LmoFB-1252dfBUuC19mSt9fePqp2CCJEY2_EL9ewdPE" />
  </div>
  <div class="image">
    <img src="https://i.picsum.photos/id/916/300/300.jpg?hmac=lP6QL2bac_8f8XYGAVNzgf2nHPlfRUNDAiDM-Kejgpg" />
  </div>

Upvotes: 1

Related Questions