3

See problem in codepen: https://codepen.io/pencillrpal/pen/QWLOLGv

I have a flex container in which I'm going to have a horizontal slider with elements as long as the full page width.

But I realized I can't control the width of the child elements, because they will always have a width that makes them fit the container, and they don't extend beyond it.

I've found a trick though. If I wrap my child divs to a div one by one it will work as I want it to.

Why does this work this way?

.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  height: 40vh;
  max-width: 100%;
  overflow-x: hidden;
  border: 5px solid black;
  margin: 0 auto;
}

.box {
  position: relative;
  width: 90vw;
  margin: 10px;
  line-height: 10vh;
  text-align: center;
  background: black;
  color: white;
  border: 5px solid red;
}
<h1>Box should have 100vw width</h1>
<div class="container">
  <div class="box">
    <h3>Box</h3>
  </div>
  <div class="box">
    <h3>Box</h3>
  </div>
  <div class="box">
    <h3>Box</h3>
  </div>
</div>

<h1>This one has though</h1>
<div class="container">
  <div>
    <div class="box">
      <h3>Box</h3>
    </div>
  </div>
  <div>
    <div class="box">
      <h3>Box</h3>
    </div>
  </div>
  <div>
    <div class="box">
      <h3>Box</h3>
    </div>
  </div>
</div>
lenkovi
  • 1,708
  • 2
  • 11
  • 16

1 Answers1

2

You can control the width of the flex children. All flex children have default flex values to control the flex-grow and flex-shrink properties. Disable these properties and you'll have control over the width.

Add these lines to your CSS.

/**
 * Disable flex grow and shrink so that it no longer tries to divide the
 * space between the .box elements.
 *
 * Use flex-basis or width to control the width of the element.
 */
.box {
    flex-grow: 0;
    flex-shrink: 0;
    flex-basis: 90vw;
    width: 90vw;
}
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32