css:之前在嵌套的div中完美无效

时间:2013-02-07 14:06:19

标签: javascript html css

我遇到了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的左侧。

3 个答案:

答案 0 :(得分:2)

Div是块元素,因此当您在div和嵌套div之前添加hello 时,显然会出现换行符。

使用嵌套div时,必须使用

jsfiddle demo

#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)

hello1分开的原因是因为1包含了一个块级元素(内部div)。

试试这个:

#test-box div:before {
  content: "hello";
}

如果您可以控制HTML,则用span(或其他内联元素)替换内部div。