批改状态:合格
老师批语:写的非常好!加油!
元素浮动后高度塌陷产生的原因:
元素浮动的基本特征:(只能水平方向浮动)
1.box浮动之后从文档流中脱离出来(意思就是它会释放原来在文档中占据的空间)
2.浮动元素浮动之后,它后面的元素会自动填充它的空间大小
3.浮动元素只会影响到它后面的元素布局、对前面的元素没有影响所以当子元素浮动后,父级里变空,就会产生高度上的缺失塌陷。
以下列举几种方法:
一、解决方法一:
给父元素container也添加一个高度.但当子元素随着内容变化的时候,父元素也需要跟着修改参数;PASS不推荐
二、解决方法二:
.给父元素container也添加一个float浮动,,可行,?但是如果父元素上还有元素的话,那就全部需要添加,也不推荐
三、解决方法三:
在container下添加一个空元素利用清除浮动来解决<div style="clear:both"></div>,这样会造成代码的冗余,不利益后期维护。
四、解决方法四:
在不给页面添加原生HTML代码的情况下利用伪元素来处理!
<style>.container::after{......clear:both;}</style>
五、解决方法五:
最简单的方法,直接利用voerflow:hidden;解决!(用到BFC)(最简单)
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>浮动元素的高度塌陷与解决办法</title><style>.container{border:3px dashed red;}.item{width: 150px;height: 150px;}.item:first-of-type{background-color:lightgreen;}.item:nth-last-of-type(2){background-color:lightcoral;}.item:last-of-type{background-color:lightblue;}/* 给3个item都浮动会发现父元素包不住子元素了 */.item{float:left;}/* 解决办法:/* 5最简单的解决办法 用到BFC块级格式化上下文*/.container{/* 可行1 */overflow:auto;/* 可行2 */overflow:hidden;}</style></head><body><div class="container"><div class="item">1</div><div class="item">2</div><div class="item">3</div></div></body></html>
浏览器运行结果:
利用绝对定位实现三列经典布局
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>三列布局-绝对定位实现</title><style>/* 初始化 */*{margin:0;padding:0;box-sizing:border-box;}li{list-style:none;}a{text-decoration:none;color:#666;}/* 页头页脚基本样式 */.header, .floot{height:40px;background-color:lightblue;}/* 页头页脚内容区基本样式 */.content{width:960px;margin:auto;}/* 页头里的li的样式 */.content ul li{float:left;padding:0 15px;/* line-height:行间距离,就是行高 */line-height:40px;}.content ul li:hover{background-color:coral;}/* 页脚 */.content p{/* text-align水平对齐方式 */text-align:center;line-height:40px;}/* 内容区用定位做 */.container{width:960px;margin:10px auto;/* 最小高度,以后写页面尽量用这样的方式去写,这样页面能撑开不会显得丑 */min-height:600px;/* 转为父级定位 */position:relative;}.container>.left{width:200px;background-color:wheat;min-height:600px;position:absolute;top:0;left:0;}.container > .main{width:540px;background-color:lightgreen;min-height:600px;position:absolute;top:0;left:210px;}.container>.right{width:200px;background-color:wheat;min-height:600px;position:absolute;top:0;right:0;}</style></head><body><!-- 页眉 --><div class="header"><div class="content"><ul><li><a href="">首页</a></li><li><a href="">618主会场</a></li><li><a href="">联系客服</a></li></ul></div></div><!-- 主体 --><div class="container"><div class="left">左侧</div><div class="main">内容</div><div class="right">右侧</div></div><!-- 页脚 --><div class="floot"><div class="content"><p>php中文网©|备案号:苏ICP备*******</p></div></div></body></html>
效果展示:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号