A
A
Andrey Ivanov2010-10-14 15:58:03
css
Andrey Ivanov, 2010-10-14 15:58:03

How to make div width dependent on content?

Tried float: left, but in this case it only works in IE and Opera.

As is


As we would like - works in IE and Opera with float: left


When placing images, if it does not fit, it is transferred to the next line, while in the place where the image did not fit, a void is formed, the block remains stretched to full width.

Answer the question

In order to leave comments, you need to log in

10 answer(s)
M
Mithgol, 2010-10-15
@Mithgol

As already mentioned above, a good wrapping of block elements to a new line can be achieved by using an inline block. I recommend for this purpose to use the following inline block code, fully tested by many months of using it in one of the main CSS files in Tradition , a Russian encyclopedia:

/*  {{Строчный блок}}
 *  http://habrahabr.ru/blogs/css/96152/
 *  ↑ http://www.smashingmagazine.com/2010/06/10/50-new-useful-css-techniques-tools-and-tutorials/
 *    ↑ http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/
 *      ↑ первоисточник
*/
.lineBlock {
   border: 0; margin: 0.3em 0.15em; padding: 0;
 
   display: -moz-inline-stack; /* ← Firefox 2 backwards compatibility */
   display: inline-block;
   vertical-align: top;
 
   /* ↓ IE6 & IE7 «hasLayout» voodoo */
   zoom: 1;
   *display: inline;
   /* ↑ IE6 & IE7 starhack ← http://www.ejeliot.com/blog/63 */
}

As you can see, this code is written in a way that is backwards compatible with Firefox 2 and IE 6 and 7.
If the border of the outer box won't fit perfectly on the borders of the inner inline boxes, then by all means try to style the outer box as an inline box as well, i.e. and assign the "lineBlock" class described by the above CSS code to it.

D
Dmitry Tyan, 2010-10-14
@crazzyDemon

try spanning div with display:inline-block property instead;

L
Lici, 2013-05-31
@Lici

display: inline-block
just ;)

D
dmomen, 2010-10-14
@dmomen

Javascript?

N
Naps, 2010-10-14
@Naps

www.artlebedev.ru/tools/technogrette/html/thumbnails-center/ Seems like
it, but yours is even easier.

V
Vlad911, 2010-10-14
@Vlad911

Have you tried setting the height?

K
Kir Shatrov, 2010-10-14
@RazoR_Empire

Damn I have the same problem =(

A
Alex Shinkevich, 2010-10-14
@aleXoid

min-width:0;
Only in IE6 will not work

S
SwampRunner, 2010-10-14
@SwampRunner

float:left; overflow:hidden;
and for bottom blocks clear:left;

B
badgoto, 2016-07-14
@badgoto

I would like to add to the question https://jsfiddle.net/badgoto/b0z9samx/ , here "@@@" is not adjacent to the text, the width of the 'content' div is larger than I would like. word-break: break-all - does not fit the task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question