ITPub博客

首页 > IT职业 > IT图书 > 解决margin-top塌陷,实现子元素动态改

解决margin-top塌陷,实现子元素动态改

IT图书 作者:tomorrowcome 时间:2021-09-09 09:30:38 0 删除 编辑

1.伪类解决margin-top塌陷:

如果两个不浮动的盒子相互嵌套,对内部的盒子设置margin-top会导致属性被自动转移到外部的盒子上,导致内部盒子的margin-top设置失败最靠谱的解决方式是为父元素添加一个伪类:
/*伪类解决margin-top塌陷*/.clearfix:before{    content:"";    display: table;
}

图片描述

解决margin-top塌陷

html>
    
    margin-top塌陷
    
    
    

2.浮动子元素动态改变父元素宽度:

在设计网页布局时,为了便于快速布局,会将子元素设为浮动元素,父元素宽度设为固定,高度不设置,这样随着子元素的添加,父元素的高度就会动态变化,但尴尬的是,浮动子元素并不能"撑开父元素的高度",于是为父元素增加伪类便成了解决这种尴尬局面最好的方式;
.clearfix:after{    content: "";    display: table;    clear:both;
}

图片描述

子元素动态改变父元素尺寸

html>
    
    浮动子元素宽度

    
    
    
    
    

小结:

以上两种情况极其常见,解决方式也很类似,所以可对两种方式做一个封装:

.clearfix:before, .clearfix:after{    content: "";    display: table;
}.clearfix:after{    clear:both;
}/*适配非主流浏览器(IE浏览器)*/.clearfix{    zoom:1;

}

以后遇到上面两种问题,只要将 小结 中的源码引入到对应的css(层叠样式表),最后在父元素class属性中 中引入clearfix即可

    
    
    
    

reset.css

h1,h2,h3,h4,h5,h6,p,body,ul,ol,dl,dd,dt,input{    /*去掉默认样式*/
    margin: 0;    padding: 0;
}ul,ol{    /*去掉左边的点或者数字*/
    list-style: none;
}a{    /*去掉下划线*/
    text-decoration: none;
}em,i{    /*去掉斜体*/
    font-style: normal;
}b,strong{    /*去掉加粗*/
    font-weight: normal;
}/*清除浮动影响 和清除margintop塌陷 合在一起的写法*/.clearfix:before,.clearfix:after{    content: "";    display: table;
}.clearfix:after{    clear: both;
}.clearfix{    /*兼容ie*/
    zoom:1;
}



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/875/viewspace-2804086/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    122
  • 访问量
    928