1.如何让文字在容器内垂直居中?
(1)方法:为容器添加line-height属性,使得line-height的值等于容器的height。
(2)代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.container{
width: 300px;
height: 500px;
margin: 50px;
background: blue;
line-height: 500px;
text-align: center;
}
.text{
color: white;
}
</style>
</head>
<body>
<div class="container">
<p class="text">我是文字</p>
</div>
</body>
</html>
(3)原理
首先应该明确line-height的含义。line-height属性的含义是设置行间的距离,简称叫行高。而文字的特点就是会以中线为基准进行显示。也就是说,我们可以做如下实现:设定一个容器div,不为其制定高度,内部的文字为其指定行高,在chrome中变换行高,我们会发现文字一直是在容器中垂直居中显示的。(这里的容器大小完全是被文本撑开的,准确的说是其line-height撑开的)
所以如果外部的div大小确定,将其内部的文字设置line-height为容器高度,从视觉效果上看就实现了文字的垂直居中。但还是应该注意并不是二者配合才生成的这种效果,而是文字本身的显示是围绕中线居中的。
2.如何实现三列布局,两侧固定宽度中间自适应?
(1)方法:利用浮动,分别对左右两侧的div设置向左右两侧浮动,再为中间的div设置相应的margin
(2)代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.container{
margin: 50px;
height: 500px;
width: 100%;
border:1px solid blue;
}
.box{
height: 100%;
border: 1px solid red;
}
.left{
width: 150px;
float: left;
}
.right{
width: 150px;
float: right;
}
.middle{
background: green;
margin-left: 150px;
margin-right: 150px;
}
</style>
</head>
<body>
<div class="container">
<div class="box left"></div>
<div class="box right"></div>
<div class="box middle"></div>
</div>
</body>
</html>
(3)原理
这里利用了默认宽度的方法。一个div,如果不为它设定宽度,那么它的宽度默认值就是100%。也就是说如果父元素宽度是当我们在此基础上为其设定margin-left和margin-right属性值,就会让这个div的宽度相应缩小。
注意,height的默认值是0。
3.如何让一个div铺满整个屏幕
(1)方法:将背景图宽度和高度设置为100%,并且设定position为fixed。
(2)代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.container{
width:100%;
height: 100%;
position: fixed;
background: black;
}
</style>
</head>
<body>
<div class="container">
</div>
</body>
</html>
(3)原理
如果只设定width和height为100%,那么宽度可以达到100%,但是高度并不会发生变化。设置了position:fixed,其含义为生成绝对定位的元素,并且相对于浏览器窗口进行定位。因此,这样设定后,整个container元素都是依据窗口进行设定的,高度的100%也就是相对于当前窗口大小的100%了。