宽高自适应
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
height: 0;
}
div{
/*宽度不写和宽度写auto就是自适应*/
/*当宽度写为100%时,是设置为浏览器窗口的宽度,不是自适应,再设置一个padding就会导致超出页面*/
/*同理高度自适应也可以实现*/
width: 100%;
/*width: auto;*/
/*也可以设置min-height来设置最小高度,这样的话即使内容太少也不会出现撑不开盒子的情况*/
/*同理也有最大高度max-height*/
height: 100px;
padding-left: 100px;
background-color: turquoise;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
高度坍塌
父元素不写高度时,子元素写了浮动,父元素会发生高度坍塌,有三个方案解决这个问题
下面这个例子高度坍塌了
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.left,.right{
width: 100px;
height: 100px;
float: left;
}
.left{
background-color: yellowgreen;
}
.right{
background-color: yellow;
}
.content{
width: 200px;
height: 200px;
background-color: turquoise;
}
</style>
<body>
<div>
<div class="left"></div>
<div class="right"></div>
</div>
<div class="content"></div>
</body>
</html>
下面是三个解决方案
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.left,.right{
width: 100px;
height: 100px;
float: left;
}
.left{
background-color: yellowgreen;
}
.right{
background-color: yellow;
}
.content{
width: 200px;
height: 200px;
background-color: turquoise;
}
/* 方案一,给父盒子设置高度,但是这样的话,高度就不是自适应的了,而且如果浮动过多的话,出现换行就会出现问题*/
/*.box{*/
/* height: 100px;*/
/*}*/
/*方案三:溢出隐藏*/
/*缺点:文字多了超出的话会被隐藏*/
.box{
overflow: hidden;
}
</style>
<body>
<div class="box">
<div class="left"></div>
<div class="right"></div>
<!--方案二:在父盒子的最后面放一个空盒子,设置一个clear:both属性-->
<!--缺点是增加了一个空标签,降低了代码的可读性,降低了网页的加载速度-->
<!--<div style="clear:both;"></div>-->
</div>
<div class="content"></div>
</body>
</html>
最完美的方案,利用伪元素
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.left,.right{
width: 100px;
height: 100px;
float: left;
}
.left{
background-color: yellowgreen;
}
.right{
background-color: yellow;
}
.content{
width: 200px;
height: 200px;
background-color: turquoise;
}
/*伪元素的写法是两个冒号,伪类的写法是一个冒号*/
/*设置第一个字母*/
div::first-letter{
font-size: 20px;
}
/*设置第一行*/
div::first-line{
font-size: 20px;
}
div::before{
content: "aaa";
}
/*这里是给box后面插入一个空标签*/
.box::after{
content: "";
clear: both;
display: block;
width: 0px;
height: 0px;
/*可见设置为隐藏,这种隐藏是占位置的隐藏,display是不占位置的隐藏*/
visibility: hidden;
}
</style>
<body>
<div class="box">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="content"></div>
</body>
</html>
窗口自适应
<!doctype html>
<html lang="en">
<head>
<style>
*{
margin: 0px;
padding: 0px;
}
div{
width: 100%;
/*此时发现没有高度,因为高度并没有父盒子可以参考的*/
height: 100%;
background-color: tomato;
}
html,body{
/*加上这句话的话就可以了*/
height: 100%;
}
</style>
</head>
<body>
<div></div>
</body>
</html>