I have the following code. How can I get the card div to only be as high as the text within it instead of taking up the entire height of the container div minus the margin I set for it?
html,
body {
margin: 0;
height: 100dvh;
background-color: darkkhaki;
}
.wrapper {
display: flex;
flex-direction: column;
margin: auto;
max-width: 1000px;
background-color: aqua;
height: 100dvh;
}
.header {
display: flex;
height: 100px;
background-color: purple;
}
.menu {
display: flex;
height: 30px;
background-color: blue;
}
.main {
display: flex;
flex-direction: row;
flex: 1 1 auto;
background-color: brown;
}
.card {
display: flex;
margin: 20px;
background-color: orange;
}
.footer {
display: flex;
height: 100px;
background-color: green;
}
```
<div class="wrapper">
<div class="header">
Header
</div>
<div class="menu">
menu
</div>
<div class="main">
main
<div class="card">
my card
</div>
</div>
<div class="footer">
footer
</div>
</div>
I have tried everything I can think of the only thing that works is if I don’t make the containing div grow to take up all the vertical space. I want it do that but don’t want the card to take up all the vertical space. I only want it to be as big as it needs to be.
3
Answers
The issue is that main is a flex, and this line:
flex: 1 1 auto
is scaling its children to fill the container.If you’d like the card to remain a flexbox, you should add
width: fit-content;
to .card to make sure that the width shrinks to fit its content + padding.A default setting on flex containers is
align-items: stretch
, which makes flex items stretch the full length of the cross axis. Simply override this setting withalign-items: flex-start
. MDNAdd this to your code:
Remove the flex style from the .card div. By default, a flex child element takes the available space, which causes the card to grow.
Set the .main div’s flex-direction to column and allow the .card div to naturally size itself according to its content.