Html 内联 div 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6072573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:42:02  来源:igfitidea点击:

Inline div elements

htmlinline

提问by Freesn?w

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.

我试图将 div 元素放在一起。问题是,即使有足够的空间让两个元素在同一行,新的 div 也会移动到下一行,如果没有足够的空间,我只需要另一个 div 去下一行.

Does anybody know how to do this?

有人知道怎么做这个吗?

回答by Spudley

Set the CSS display style to display:inline-block;.

将 CSS 显示样式设置为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)

(但请注意,旧版本的 IE 存在一些兼容性问题)

回答by George Cummins

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 是块级元素,因此默认情况下它们将始终占据整行。改变这种情况的方法是浮动 div:

<div style="float: left"></div>

回答by MarioRicalde

Use float's and margin's; that way when there's no space you can just put overflow:hiddento the containerhide the rest of the divinstead of making it go to the next line.

使用float's 和margin's; 这样,当没有空间时,您可以将其余overflow:hiddencontainer隐藏起来,div而不是让它转到下一行。

CSS

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

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/kurtheitroad/UupbG/1/

演示在这里:http: //jsfiddle.net/kurtheitroad/UupbG/1/

回答by Matías Fidemraizer

You need to use floatCSS rule. Just use some class or identifier and set floatto leftor right.

您需要使用floatCSS 规则。只需使用一些类或标识符并设置floatleftor right

回答by Ahmed Magdy

Make sure that you have a fixed width to the divs

确保你有一个固定的宽度到divs