作为一个初级的前端工程师,在开发的过程中遇到了许多问题,其中使元素垂直居中这个问题难住了我,可能在大家看来这是一个非常小的问题,但是却困扰了我很长时间,于是决定做一个总结!!!

废话不多说,直接上代码,里面有我的思考过程

案例一

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>div实现垂直居中</title>
</head>
<style>
.abc {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: ;
top: ;
bottom: ;
right: ;
margin: auto;
} .box {
position: relative;
width: 500px;
height: 500px;
background: red;
display: inline-block;
}
</style>
<div class="box">
<div class="abc"> </div>
</div> <body>
</body> </html>

案例二(文字的水平垂直居中)

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Document</title>
</head> <body>
<style>
div {
height: 300px;
width: 200px;
display: table;
background: #;
} span {
display: table-cell;
vertical-align: middle;
}
</style>
<div>
<span>我是span</span>
</div>
</body> </html>

案例三

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>div实现垂直居中</title>
</head>
<style>
.abc {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: %;
top: %;
margin-left: -100px;
margin-top: -100px;
} .box {
position: relative;
width: 500px;
height: 500px;
background: red;
display: inline-block;
}
</style>
<div class="box">
<div class="abc"> </div>
</div> <body>
</body> </html>

案例四

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>div实现垂直居中</title>
</head>
<style>
/*
table-cell实现居中
将父盒子设置为table-cell元素,设置
text-align:center,vertical-align: middle;
子盒子设置为inline-block元素
*/ .ok {
width: 200px;
height: 200px;
background: red;
display: table-cell;
/*这个必须是table-cell*/
/*父级是一个小表格,表格默认是放文字的,子集是一个小果冻元素,给父级设置vertical-align:middle使元素垂直居中*/
text-align: center;
vertical-align: middle;
} .innerBox {
width: 100px;
height: 100px;
background: green;
display: inline-block;
/*注意:里面的元素必须是inline-block*/
}
</style> <body>
<div class="ok">
<div class="innerBox">
</div>
</div>
</body> </html>

案例五

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Document</title>
</head> <body>
<style>
/* 注意:该方法值适合文字的水平垂直居中;
* 父级高度固定,嵌套行内元素
*关键属性:父级:diaplay:tabel; 子集:display:tabel-cell; vertical-align:middle;
*/ .div {
height: 300px;
width: 200px;
display: table;
/*这么理解:父级是一个固定宽度高度的大表格*/
background: #;
} .span {
display: table-cell;
/* 子集是父级表格里面的一个小格,设置display:table-cell,给父级设置垂直居中*/
vertical-align: middle;
}
</style>
<div class="div">
<div class="span">sddddd</div>
</div>
</body> </html>
05-11 10:48