Html 如何强制跨度与 div 位于同一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19023411/
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
How can I force spans to be on the same line as a div?
提问by Phish
I have a simple structure of:
我有一个简单的结构:
<div></div><span></span><span></span>
but I want to force them all on one line! at the moment, they appear:
但我想强迫他们都在一条线上!此刻,它们出现:
<div />
<span /><span />
unfortunately, I HAVE to have the first element as a div; the div is acting as a bar from a bar chart (so rounded corners, width = jquery stuff, no content and block colour inside), the next span is the value the bar represents and the last span is what the value is associated to.
不幸的是,我必须将第一个元素作为 div;div 充当条形图中的一个条(所以圆角,宽度 = jquery 的东西,里面没有内容和块颜色),下一个跨度是该条代表的值,最后一个跨度是该值所关联的值。
so I want
所以我想要
[____________] 25% ObjectA
[________________________] 50% ObjectB
[______] 12.5% ObjectC
[______] 12.5% ObjectD
and not
并不是
[____________]
25% ObjectA
[________________________]
50% ObjectB
[______]
12.5% ObjectC
[______]
12.5% ObjectD
回答by Dylan MacKenzie
Put the CSS property display: inline-block
on the div to make it act like an inline element instead of taking up the whole line.
将 CSS 属性display: inline-block
放在 div 上,使其表现得像一个内联元素,而不是占据整行。
Edit:
编辑:
@Mr_Green's suggestion to use the after
pseudo-element to clear each line is absolutely necessary to prevent a broken layout.
@Mr_Green 建议使用after
伪元素清除每一行对于防止布局损坏是绝对必要的。
回答by Mr_Green
The suggestion of Dylan will work but sometimes if one of the div's width is very less then the next div will come inline with this div element. see this fiddle. So, my suggestion is to use :after
pseudo element which will be display: block
. This pseudo element will be for the last span in every bar section.
Dylan 的建议会起作用,但有时如果 div 的宽度之一非常小,那么下一个 div 将与此 div 元素内联。看到这个小提琴。所以,我的建议是使用:after
伪元素,它将是display: block
. 这个伪元素将用于每个条形部分的最后一个跨度。
div {
/* width and height are just for example */
width: 100px;
height: 50px;
background-color: red;
display: inline-block;
}
div+span+span:after { /* last span element's pseudo element */
content:"";
display: block;
}
回答by Nils Kaspersson
Since <div>
elements default to display: block
, which takes up all available width, you'll need to set it to display: inline-block
. You'll also need to break the lines manually with a <br>
, or do something fancy on the last <span>
to make it fill the rest of the available space.
由于<div>
元素默认为display: block
,占用所有可用宽度,因此您需要将其设置为display: inline-block
。您还需要使用 a 手动断行<br>
,或者在最后一个做一些花哨的事情<span>
以使其填充剩余的可用空间。
Alternatively, wrap each row in another block-level element (such as another <div>
) to create new rows.
或者,将每一行包装在另一个块级元素(例如 another <div>
)中以创建新行。
回答by Derzu
At your span add the CSS property:
在您的跨度添加 CSS 属性:
white-space: nowrap;