As far as I know, width of a flex item adjusts to its content(when flex-direction: row;
).
Here you see, the width of second .item
is too long even though I set the width of h1
to 50%.
* {
margin: 0;
padding: 0;
}
.container {
display: flex;
justify-content: space-between;
border: 2px solid red;
padding: 10px;
}
.item {
border: 1px solid black;
}
.test {
width: 50%;
}
<div >
<div >Lorem ipsum dolor sit amet.</div>
<div >
<h1 >
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi,
quo.
</h1>
</div>
</div>
But when I use px
instead of %
, the result that I wanted comes out. (Please view it in a full page)
* {
margin: 0;
padding: 0;
}
.container {
display: flex;
justify-content: space-between;
border: 2px solid red;
padding: 10px;
}
.item {
border: 1px solid black;
}
.test {
width: 400px;
}
<div >
<div >Lorem ipsum dolor sit amet.</div>
<div >
<h1 >
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi,
quo.
</h1>
</div>
</div>
I can't understand how %
is calculated in the first code. Can somebody help? Thanks
CodePudding user response:
You have to apply the width on the .item
element.
* {
margin: 0;
padding: 0;
}
.container {
display: flex;
justify-content: space-between;
border: 2px solid red;
padding: 10px;
}
.item {
border: 1px solid black;
}
.item:nth-child(2) {
width: 50%;
}
<div >
<div >Lorem ipsum dolor sit amet.</div>
<div >
<h1 >
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi, quo.
</h1>
</div>
</div>
CodePudding user response:
You are not applying 50% to children (.item) but rather to (.test), which is not child of display:flex
. Fix it and you'll get result!
* {
margin: 0;
padding: 0;
}
.container {
display: flex;
justify-content: space-between;
border: 2px solid red;
padding: 10px;
}
.item {
border: 1px solid black;
width: 50%;
}
.test {
background: yellow;
}
<div >
<div >Lorem ipsum dolor sit amet.</div>
<div >
<h1 >
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi,quo. </h1>
</div>
</div>