Inline div elements

天涯浪子 提交于 2020-01-02 05:43:05

问题


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?


回答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)




回答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>



回答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/




回答4:


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




回答5:


Make sure that you have a fixed width to the divs



来源:https://stackoverflow.com/questions/6072573/inline-div-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!