Inline div elements
Solution 1
Set the CSS display style to display:inline-block;
.
This allows the element to keep it's block-like functionality, while also allowing it to be displayed inline. It's a half-way house between the two.
(But note that there are some compatibility issues with older versions of IE)
Solution 2
Divs are block level elements, so by default they will always occupy an entire line. The way to change this is to float the divs:
<div style="float: left"></div>
Solution 3
Use float
's and margin
's; that way when there's no space you can just put overflow:hidden
to the container
hide the rest of the div
instead of making it go to the next line.
CSS
.container {
width:500px;
background:#DADADA;
overflow:hidden; /* also used as a clearfix */
}
.content {
float:left;
background:green;
width:350px;
}
.sidebar {
width:155px; /* Intentionaly has more width */
margin-left:350px; /* Width of the content */
background:lime;
}
HTML
<div class="container">
<div class="content">Content</div>
<div class="sidebar">Sidebar</div>
</div>
In this demo you can see: floats, margin+floats, display:inline-block.
Demo here: http://jsfiddle.net/kuroir/UupbG/1/
Freesnöw
Updated on May 21, 2020Comments
-
Freesnöw about 4 years
I'm trying to put div elements right next to each other. The problem is, even if there is enough room for the two elements to be on the same line, the new div moves itself to the next line, I need the other div only to go to the next line if there isn't enough room.
Does anybody know how to do this?
-
zzzzBov about 13 yearsyou should use
span
elements if you need generic inline elements.
-
-
NGLN about 13 yearsAnd to start a next inline element on a new line, add style="clear: both" to that element.
-
George Cummins about 13 yearsOP said: " I need the other div only to go to the next line if there isn't enough room" so in this case, no clearing should be used. That's good advice for other situations, though.
-
NGLN about 13 yearsSorry for the unclarity; I meant an element, other than the div's in question. Probably OP has more markup beyond those. ;)
-
DavidJCobb about 13 yearsWouldn't inline-block be a better solution? Floats tend to be pretty messy; clearing the containers, preventing issues with other floats, making sure text wraps around them properly...
-
George Cummins about 13 yearsHere is a detailed comparison of the two methods: ternstyle.us/blog/float-vs-inline-block There are pros and cons for each. For me, the most compelling argument is that IE 7 and earlier do not deal with inline-block appropriately. I often find it easier to deal with the consequences of floating than to create alternate styles for IE 7 and earlier.
-
George Cummins about 13 yearsSee ternstyle.us/blog/float-vs-inline-block for a detailed comparison, as well as a discussion of the compatibility issues with IE 7 and earlier.