I have a parent element, with two elements inside:
<div class="parent">
<div class="child">
one
</div>
<div class="child">
two
</div>
</div>
Currently, the .parent is 100% wide. I would like it only to be the width of the two children.
.parent {
display: flex;
background-color: aliceblue;
}
How can I make the parent to be the width of it's contents, and not wider?
See codepen for a live demo.
Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.
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.
Getting the child of a flex-item to fill height 100%Set position: relative; on the parent of the child. Set position: absolute; on the child. You can then set width/height as required (100% in my sample).
It CAN have a wider width by giving both elements explicit widths, obv with the inner element being wider, and the parent element using overflow: visible; so that the child element's content can be seen. You could also give the child element a negative margin to bump it outside of its container's bounds.
Change the parent's display from flex
to inline-flex
.
codepen demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With