HTML Part
<div >
<div >hi</div>
</div>
CSS Part
.container{
width: 500px;
aspect-ratio: 1/1;
margin: auto;
display: flex;
gap: 50px;
flex-wrap: wrap;
background: rgba(0, 1000, 0, 0.1);
justify-content: center;
}
.card{
aspect-ratio: 1/1;
width: 50px;
background: rgba(0, 1000, 0, 0.1);
}
With the above code I expect that the card
should be a squre of 50px. But surprisingly its height becomes 500px. i.e. same as the parent.
Please explain why it is happning.
If I remove the display: flex;
from the container
then the card
becomes perfect squre as expected.
CodePudding user response:
Specifying the height will solve your code problem and will allow the display flex to still dictate where the card will be inside of the container. Take a look at this code.
.container{
width: 500px;
aspect-ratio: 1/1;
margin: auto;
display: flex;
gap: 50px;
flex-wrap: wrap;
background: rgba(0, 1000, 0, 0.1);
justify-content: center;
align-items: center; /*To center the card vertically inside of the container*/
}
.card{
height: 50px;
width: 50px;
background: rgba(0, 1000, 0, 0.1);
/*To center the text inside of the .card*/
display: flex;
justify-content: center;
align-items: center;
}
<div >
<div >hi</div>
</div>
CodePudding user response:
Why it's happening: the default value of align-content
and align-items
is stretch
. align-content: stretch
makes the flex line fill the flex container's cross size (cross size is height in your example because it is a row flexbox). Then align-items: stretch
makes the flex item's cross size fill the line's cross size, which was just stretched to be the container's cross size.
See https://drafts.csswg.org/css-flexbox/#valdef-align-items-stretch. It says "If the cross size property of the flex item computes to auto [then don't stretch]."
The purpose of that conditional is so that stretching doesn't override a specified cross size on the item. (If someone put height: 200px
inside a height:300px
flexbox, the browser shouldn't override that height: 200px
)
But because your item has height:auto
, the item stretches.
This part of the flex spec was written before aspect-ratio
existed. Maybe it should expand the cases where the items aren't stretched to include items that have a specified aspect-ratio and a definite main size like your example, but... it doesn't. So this is what we got :(
So, if you don't want your aspect-ratio item to stretch, you can do any of these things:
- specify a
height
- put
align-content: center
(orstart
orend
) on the container - put
align-items: center
(orstart
orend
) on the container - put
align-self: center
(orstart
orend
) on the item