1. 一个200×200的div在不同分辨率上下左右居中,用css实现
方法一:
.box{
width:200px;
height: 200px;
background-color: antiquewhite;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px; //margin-left是做边距,是宽度
margin-top: -100px; //left是定位盒子左上角左边位置的一个点
}
方法二:
.box{
width:200px;
height: 200px;
background-color:blue;
position: absolute;
top: 0;
right: 0;
left:0;
bottom: 0;
//设置top:0,left:0,right:0,bottom:0本质目的,是让子盒子四边与父容器间距为0,而子盒子没有明确宽高,自然被拉伸到完全填满父容器了。这也是为何让盒子垂直水平居中时必须要有明确宽高的原因
//就像四个方向有相同的力在拉这个盒子,配上margin:auto让这个盒子的位置保持中立,来达到盒子处于正中心的目的
margin: auto;
}
2.写一个左中右布局占满屏幕,其中左,右两块固定宽200,中间自适应宽,要求先加载中间块,写出结构及样式
<style>
*{
margin: 0;
padding:0;
}
.main>div{
float: left;
}
.container{
width: 100%;
}
.content{
background:#B63A3C;
margin-left: 200px;
margin-right: 200px;
}
.left{
background:aqua;
width: 200px;
margin-left: -100%;
}
.right{
background:cornflowerblue;
width: 200px;
margin-left: -200px;
}
</style>
</head>
<body>
<div class = "main">
<div class = "container">
<div class = "content">中间</div>
</div>
<div class = "left">左边</div>
<div class = "right">右边</div>
</div>
3.简述清除浮动(清除闭合)的几种方式
(1)添加一个盒子,加入clear:both,目的在于这个添加的空白盒子周围不允许有浮动元素,因此撑开了main父元素的高度。
缺点:多了一个div盒子
<style>
*{
margin: 0;
padding:0;
}
.main{
border:5px solid red;
}
.div1{
width: 100px;
height: 100px;
background:green;float: left;
}
.div2{
width: 100px;
height: 100px;
background:yellow;float: left;
}
.div3{
width: 100px;
height: 100px;
background:blue;float: left;
}
.clear{
background:black;
width: 300px;
height: 100px;
clear:both;
}
</style>
</head>
<body>
<div class = "main">
<div class = "div1"></div>
<div class = "div2"></div>
<div class = "div3"></div>
<div class = "clear"></div>
</div>
(2)给父元素加入: overflow: hidden;实际上创建了一个超级属性BFC,(overflow的值不为visible为BFC被显式触发的条件之一),此超级属性反过来决定了"height:auto"是如何计算的。在“BFC布局规则”中提到:计算BFC的高度时,浮动元素也参与计算。因此,父元素在计算其高度时,加入了浮动元素的高度,“顺便”达成了清除浮动的目标,所以父元素就包裹住了子元素。
.main{
border:5px solid red;
overflow: hidden;
}
(3)最常用一种方式(after)
:after 的意思是在.main内部的最后加入伪元素:after,
首先要显示伪元素,所以display:table,
然后伪元素加入空内容,以便伪元素中不会有内容显示在页面中,所以, content:"";
其次,为使伪元素不影响页面布局,将伪元素高度设置为0,所以, height:0,
最后,要清除浮动,所以,clear:both。
.main:after{
display:table;
content: "";
height:0;
clear:both;