我遇到了css :before
和:after
的问题。这是我的HTML:
<div id = "test-box">
1
</div>
这是我的css:
#test-box:before{
content: "hello";
}
当我运行时,它完美地工作并打印:hello 1
但是当我在我现有的div
中添加另一个div
时,它不起作用。这是新的HTML:
<div id = "test-box">
<div>1</div>
</div>
在这种情况下,浏览器会打印:
hello
1
我需要留在1的左侧。
答案 0 :(得分:2)
Div是块元素,因此当您在div和嵌套div之前添加hello 时,显然会出现换行符。
使用嵌套div时,必须使用
#test-box div:before{
content: "hello";
}
<强>更新强> jsfiddle demo
#test-box:before{
content: "hello";
}
#test-box div {
display: inline;
}
答案 1 :(得分:1)
如果您有嵌套div,请使用此CSS:
#test-box div:before{
content: "hello";
}
选择器选择<{1}} 元素div
中的test-box
,并在此之前添加文本,而不是在外部div之前添加文本。
1
在新行上的原因是因为divs
是块元素。您的原始CSS在内部<div>
标记之前添加了文本,从而在添加的文本后生成换行符。
所以,这件事发生了:
<div id="test-box">
hello
<div> <!-- the div starting here causes the following text to be displayed on a new line -->
1
</div>
</div>
使用修改后的CSS,这将是结果,而不是:
<div id="test-box">
<div>
hello1
</div>
</div>
如果您必须将其放在外部div中,请将其添加到您的css:
#test-box div{
display: inline-block;
}
(保留问题的另一行)。
这会阻止内部div
换行到新行。
<强> Example 强>
答案 2 :(得分:1)
hello
与1
分开的原因是因为1
包含了一个块级元素(内部div)。
试试这个:
#test-box div:before {
content: "hello";
}
如果您可以控制HTML,则用span(或其他内联元素)替换内部div。