html - 应用 CSS float 属性时,会重绘其父级的尺寸

标签 html css styles css-float

给定以下 HTML 代码:

<html>
<body>
<head>
<style>

#myDiv{
  background:orange;
  width:300px;

}

.a{
  margin:5px;
  background:purple;
}

</style>
</head>
<body>
<div id="myDiv">
  <p class="a">A<br>A</p>
  <p class="b">B</p>
</div>
</body>
</html>

为什么当我在 .a 中添加 float:right 时,myDiv 会缩小?

你同意我的回答吗?

Because CSS floats are positioning properties. The paragraph referenced to as 'a' is positioned with a float CSS property and breaks out of the flow of the div 'myDiv'. That's why the 'a' element is positioned at the right corner of the div 'myDiv'. The browser renders 'myDiv' without the floating paragraph 'a'. That is why the browser only draws a background behind the node value of the paragraph referenced to as 'b' and stretches it 300 pixels wide, following the CSS declaration of the html head element.

最佳答案

你可能喜欢这个

<div id="myDiv">
  <p class="a">A<br>A</p>
  <p class="b">B</p>
  <div style="clear:both;"></div>
</div>

关于html - 应用 CSS float 属性时,会重绘其父级的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800504/

相关文章:

html - 环绕式 CSS 边框动画

html - 使用CSS通过按标签聚焦输入

javascript - 从数组内容设置 div id

javascript - 是否有一个 API 可以获取位置并查找其坐标?

html - 使用 CSS 定位 reCAPTCHA 小部件

jquery - 如何以固定高度 UL 滚动 LI 元素?

android - 如何以编程方式在 View 中设置样式属性

jquery - 如何使元素居中同时保持 Bootstrap 的大小?

html - CSS 表格宽度

html - 网页右侧溢出