Freesnöw
Freesnöw

Reputation: 32143

Inline div elements

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?

Upvotes: 6

Views: 44174

Answers (5)

MarioRicalde
MarioRicalde

Reputation: 9487

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/

Upvotes: 3

Ahmed Magdy
Ahmed Magdy

Reputation: 6030

Make sure that you have a fixed width to the divs

Upvotes: -2

Spudley
Spudley

Reputation: 168685

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)

Upvotes: 13

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

You need to use float CSS rule. Just use some class or identifier and set float to left or right.

Upvotes: 0

George Cummins
George Cummins

Reputation: 28906

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>

Upvotes: 5

Related Questions