< div>嵌套在< p>中 [英] <div> nested in <p>

查看:81
本文介绍了< div>嵌套在< p>中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>转换为相同的内容.因此,我得到了:

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>既可以是emty元素(如<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.

推荐答案

<p>类似的<div>标签是块级元素,这意味着它旨在包含其自己的带有换行符的块.尝试将<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-in-the-p-tag-right-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.

这篇关于&lt; div&gt;嵌套在&lt; p&gt;中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆