0

Situation

  • I have a set of <div> elements inside a container <div>.
  • The width of the inner <div> are set to relative sizes in percentage.
  • Sometimes the sum of the widths of the inner divs are over 100%.

How it is

What happens currently, is that the inner divs are squashed in a way to fit the container.

<div id="container" style="float:left; display:flex; width: 500px">
    <div style="background-color: black; width: 90%">test</div>
    <div style="background-color: red; width: 90%">test</div>
</div>

https://jsfiddle.net/pgvhfb9e/2/

As you can see, the red one is exactly the same size as the black one.

What I want

What I need is that the last div is simply cut off at the end of the container. Therefore, the red one should only be 10% while the black one is 90%.

ataraxis
  • 1,257
  • 1
  • 15
  • 30

1 Answers1

1
  • flex-shrink: 0 on the child elements
  • overflow: hidden on the parent

This prevents child elements from being shrunk to fit within the parent, and prevents your "10% visible" child element from being visible outside the bounds of the parent element.

<div id="container" style="float:left; display:flex; width: 500px; overflow: hidden;">
  <div style="background-color: black; width: 90%; flex-shrink: 0;">test</div>
  <div style="background-color: red; width: 90%; flex-shrink: 0;">test</div>
</div>

And here's a variant using the flex shorthand property to set flex-grow, flex-shrink, and flex-basis properties all at once.

<div id="container" style="float:left; display:flex; width: 500px; overflow: hidden;">
  <div style="background-color: black; width: 90%; flex: 1 0 auto;">test</div>
  <div style="background-color: red; width: 90%; flex: 1 0 auto;">test</div>
</div>
simmer
  • 2,639
  • 1
  • 18
  • 22