Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make div NOT auto stretch to container width

Tags:

html

css

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?

like image 917
Sony packman Avatar asked Jul 27 '12 00:07

Sony packman


People also ask

How do I stop my div from stretching?

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.

How can I let a div automatically set it own width?

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.

How do you make a div take up the rest of the 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.

How can I make div occupy full height of container?

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.


2 Answers

You'd have to set the display property to inline-block

<div style="display: inline-block">Text</div>
like image 192
Ross McLellan Avatar answered Oct 02 '22 15:10

Ross McLellan


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.

like image 36
Ben Avatar answered Oct 02 '22 15:10

Ben