Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it really impossible to make a div fit its size to its content?

Tags:

html

width

size

I'd like to clarify whether it's possible or not to make a div fit its size based on the content's size without having to make elements float or having to make their position absolute. Is it possible?

like image 531
Gabriele Cirulli Avatar asked May 05 '11 19:05

Gabriele Cirulli


People also ask

How do I resize a div by content?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

Is a div 100% width by default?

auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.

How do I make a div fit in a div?

If you want the child divs to fit the parent size, you should put a margin at least of the size of the child borders on the child divs ( child. margin >= child. bordersize ).

How do I force a div to full width?

What you could do is set your div to be position: absolute so your div is independent of the rest of the layout. Then say width: 100% to have it fill the screen width. Now just use margin-left: 30px (or whatever px you need) and you should be done.


2 Answers

CSS display setting

It is of course possible - JSFiddle proof of concept where you can see all three possible solutions:

  • display: inline-block - this is the one you're not aware of

  • position: absolute

  • float: left/right

like image 163
Robert Koritnik Avatar answered Sep 20 '22 15:09

Robert Koritnik


You can use display: inline-block.

like image 43
Matt Ball Avatar answered Sep 22 '22 15:09

Matt Ball