My question is simple:
Can you stop a div from auto-stretching to the width of its containing element and have it only stretch horizontally as much as the content inside it forces?
Kind of like the default vertical behavior of divs but applied horizontally. Is this possible?
By default, the child elements of a flexbox container will stretch vertically to fill the height of the container. This can be prevented by using the align-self property on the child element that you do not want to stretch. This Pen is owned by dev on CodePen.
Set display to inline-block to make the div width fit to its content. Use position: relative and left: 50% to position its left edge to 50% of its containing element. Use transform: translateX(-50%) which will "shift" the element to the left by half its own width.
The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely.
Answer: Set the 100% height for parents too And we all know that the default value of the height property is auto , so if we also set the height of <body> and <html> elements to 100%, the resulting height of the container div becomes equal the 100% height of the browser window.
You'd have to set the display
property to inline-block
<div style="display: inline-block">Text</div>
Actually, display:inline
will have better browser support, but may not achieve the results you want, it will keep the div in line with the content, a la <span>
.
There's two types of elements: block, and inline. Block elements stretch to width and break the line. Inline stretches to content and stays inline. (!)
display:inline-block
is getting better support, but the older browsers won't do it.
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