lt;divgt; nested in lt;pgt;(div嵌套在 lt;pgt;)
问题描述
在学习网络开发时,我遇到了一个问题.这是我的代码:
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.
这篇关于<div>嵌套在 <p>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:<div>嵌套在 <p>


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01