Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two 50% divs with white-space:nowrap elements inside a flex container

Tags:

html

css

flexbox

I want to have a parent div that holds two 50% width children divs that resize with content.

One of them has an h3 with white-space:nowrap; and this causes the div to grow past 50%.

I can force the div to return to 50% width using min-width:0; but the h3 now overflows.

So I either get a different width on the child divs or an overflow from the h3 inside one of them.

Is it possible to make them have the same 50% width even with elements that have white-space:nowrap; inside?

Check out the problem here: http://codepen.io/anon/pen/VjPwLm?editors=1100

#parent {
  background: whitesmoke;
  display: inline-flex;
}
#left {
  background: rgba(10, 200, 250, 0.5);
  flex-basis: 0;
  flex-grow: 1;
}
#right {
  background: rgba(250, 200, 10, 0.5);
  flex-basis: 0;
  flex-grow: 1;
  /*min-width:0;*/
  /* Turn this on to see the h3 overflow */
}
h3 {
  white-space: nowrap;
}
<div id="parent">
  <div id="left">Captain Deadpool</div>
  <div id="right">
    <h3>Very long title that does not entirelly fit into the div</h3>
  </div>
</div>
like image 976
André Casal Avatar asked Jun 23 '16 19:06

André Casal


People also ask

What is 50% Flex CSS?

flex-basis defines the default size of an element before the remaining space is distributed. So in this case, you have defined all a children` to 50%.

How do I remove space between Flex items in CSS?

To override this behavior, apply align-content: flex-start to the container. When you're working in a single-line flex container (i.e., flex-wrap: nowrap ), the properties to use to distribute space along the cross axis are align-items and align-self .

How do you set an element as the Flex container?

To create a flex container, we set the value of the area's container's display property to flex or inline-flex . As soon as we do this the direct children of that container become flex items.


1 Answers

If I understand correctly, you want the left flex item to be as wide as the long title.

Then, you can:

  • Use min-width: 100% on both flex items to make them as wide as the concatenation of their texts. Then, they will be equally wide.

  • But they are too wide, because the text of the first flex item is included. Use width: 0 to ignore it.

#parent {
  background: whitesmoke;
  display: inline-flex;
}
#left, #right {
  min-width: 100%;
}
#left {
  background: rgba(10,200,250,0.5);
  width: 0;
}
#right {
  background: rgba(250,200,10,0.5);
  white-space: nowrap;
}
<div id="parent">
  <div id="left">Captain Deadpool</div>
  <div id="right"><h3>Very long title that does not entirelly fit into the div</h3></div>
</div>
like image 128
Oriol Avatar answered Nov 15 '22 10:11

Oriol