Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 box-flex - box size differs depending on inner content

Tags:

css

Can someone tell me what i am doing wrong here? I want the boxes to be the EXACT same width between both divA and divB. Just because divB box has slightly longer text in 'p2' should not change the width of the entire box. I don't want to use hard pixel widths for the 'p1' so that it can be flexible for viewport widths. I just want p1 box to always be half the size of p2, regardless of inner content. Can someone help me out or suggest a better method??

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css"> 
div
{
display:-moz-box; /* Firefox */
display:-webkit-box; /* Safari and Chrome */
display:box;
width:100%;
border:1px solid black;
}

#p1
{
-moz-box-flex:1.0; /* Firefox */
-webkit-box-flex:1.0; /* Safari and Chrome */
box-flex:1.0;
text-align:right;
border:1px solid red;
}

#p2
{
-moz-box-flex:2.0; /* Firefox */
-webkit-box-flex:2.0; /* Safari and Chrome */
box-flex:2.0;
text-align:left;
border:1px solid blue;
}
</style>
</head>
<body>

<div id='divA'>
<p id="p1">Hello</p>
<p id="p2">Column 2</p>
</div>

<div id='divB'>
<p id="p1">Hello</p>
<p id="p2">Why is this box larger</p>
</div>

</body>
</html>
like image 506
29er Avatar asked Dec 06 '11 18:12

29er


People also ask

How do you give something a different width to flex?

A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.


2 Answers

If you give the children an explicit width, they will behave.
The flex value will override these widths, giving you the desired layout. The boxes just need a value to start from. Without a defined width, they shrink to their content's width, then the flex value is applied.

See here: http://jsfiddle.net/ZBE7r/

...
#p1, #p2 {
    width: 1px;
}
...

It only works if they all have the same explicit width (can be any value: 0, 1px, 100%, etc)

like image 90
Lachlan Arthur Avatar answered Oct 31 '22 08:10

Lachlan Arthur


Found this quote. This might explain why it's doing that.

"That sounds like it's working as expected. The flexing is only applied after the preferred sizes of the boxes have been calculated. So in your example it sounds like the total box width adds up to something far bigger than the container width. The browser then uses to flex property to decide which boxes to squash to make them fit. Your middle box has the most flex so therefore it is squashed the most" link

like image 34
Recognizer Avatar answered Oct 31 '22 08:10

Recognizer