<div>嵌套在 &lt;p&gt;

2022-01-18 00:00:00 tags html

在学习网络开发时,我遇到了一个问题.这是我的代码:

While learning web dev i've stuck a problem. That's my code:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
    p
    {
        background: blue;
    }

    .primary
    {
        color: red;
    }
    </style>
</head>
<body>
    <p>
        text1
        <div class="primary">
            text
        </div>
        text2
    </p>
</body>
</html>

由于某些原因,浏览器将 <p> 转换为 <p>text</p></p> 到相同.所以不是 <div> 嵌套在 <p> (我实际上在源代码中写的!)我得到了这个:

For some reason browsers convert <p> to <p>text</p> and </p> to the same. So instead of <div> nested in <p> (What I've actualy writen in source!) I get this:

...
<body>
<p>
text1
</p>
<div class="primary">
    text
</div>
text2
<p></p>
</body>
...

我认为这是因为 <p> 既可以是空元素(如 <br>)也不是空元素(如 <div>).你能解释一下我的问题并给出解决方案吗?谢谢.

As I suppose that happens because <p> can be both an emty element (like <br>) and not empty element (like <div>). Can you please explain me the problem and give a solution. Thank you.

推荐答案

<div>标签,和<p>一样是块级元素,意味着它被设计成包含它自己的块,周围有换行符.尝试将 <div> 嵌套在 <p> 内不太可能做你想做的事情,因为它没有多大意义.<p> 是一个段落,它不应包含块级元素.这个问题可能是相关的:

The <div> tag, like <p> is a block level element, which means that it is designed to contain it's own block of with newlines around it. Trying to nest a <div> inside of a <p> is not likely to do what you want as it doesn't make much sense. A <p> is a paragraph, and it should contain no block level elements. This question may would be related:

https://stackoverflow.com/questions/4291467/nesting-block-level-elements-inside-the-p-tag-right-or-wrong

尝试改用 <span>,因为 <span> 是一个内联元素,旨在显示在段落内.如果您确实需要多个块级元素,请考虑根本不使用 <p> ,或者将它们用作最内部的块级元素而不是外部元素.

Try using <span> instead, because <span> is an inline element, which is designed to be displayed inside of a paragraph. If you really do need multiple block level elements there, consider not using the <p> there at all, or using them as the inner most block level element rather than an outer element.

相关文章