今天在用移动端的时候发现个问题,html,body 设置 height:100% 会出现纵向滚动条
<!DOCTYPE html>
<html>
<head>
<title>html5</title>
<style>
html, body {
height: 100%;
}
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div style="height: 100%;">
<div style="margin-top: 44px;height: 200px;"></div>
</div>
</body>
</html>
出现原因:
margin
重叠(margin collapse)是指当两个垂直排列的块级元素的 margin
发生重叠时,最终的外边距会取两个 margin
值中的较大者,而不是两个 margin
的和。换句话说,margin
重叠会导致元素之间的实际间距被缩减。
因为子元素设置了 margin-top 且是最大值,所以父子的外边距都是子元素的外边距值了。
解决方法就是触发 BFC
解决方法一:
父元素设置 overflow: hidden; 或是 overflow: auto;
解决方法二:
父元素或子元素设置浮动
float: left
解决方法三:
父元素设置 position: relative;
子元素设置 position: absolute;
解决方法四:
父元素设置 ::before 让父元素和子元素不相临,就不会有外边距重叠问题
.parent::before {
content: "";
display: table;
}
或是父子元素间插入一个 display: flex; 的元素,触发 BFC
<span style="display: none"></span>
解决方法五:
父元素使用Flexbox或Grid布局,也可以避免外边距合并的问题。
解决方法六:
为父元素添加边框或内边距:通过给父元素添加border-top
或padding-top
,可以阻止子元素的margin-top
与父元素的margin-top
合并。
border-top: 0.1px solid red;
或是
padding-top: 0.1px;