html body 设置heigth 100%,body内元素设置margin-top出滚动条(margin 重叠问题)

今天在用移动端的时候发现个问题,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-toppadding-top,可以阻止子元素的margin-top与父元素的margin-top合并。

border-top: 0.1px solid red;
或是
padding-top: 0.1px;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值