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

今天在用移动端的时候发现个问题,html,body 设置 height:100% 会出现纵向滚动条




html5



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

出现原因:

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

 解决方法五:

父元素使用Flexbox或Grid布局,也可以避免外边距合并的问题。

 解决方法六:

为父元素添加边框或内边距‌:通过给父元素添加border-toppadding-top,可以阻止子元素的margin-top与父元素的margin-top合并。

border-top: 0.1px solid red;
或是
padding-top: 0.1px;

你可能感兴趣的:(html,git,前端)