<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>实现元素垂直居中</title>
<style>
.box{
background-color: pink;
overflow: hidden;
margin-bottom: 30px;
}
.text{
background-color: #aaa;
margin: 100px auto;
}
.box2 input{
margin: 30px 0;
}
.box3 a{
line-height: 100px;
}
.box4{
height: 500px;
position: relative;
}
.box4 span{
display: inline-block;
width: 200px;
height: 200px;
background-color: #eee;
position: absolute;
top: 50%;
margin-top: -100px;
}
</style>
</head>
<body>
<b>方法一:</b>针对块级元素在块级元素里垂直居中比较容易,父级元素不设置高度,设置overflow: hidden;(记得!!)子元素也就是需要居中的这位,margin值上下设置成一样的。
<div class="box box1">
<div class="text">块级元素</div>
</div>
针对行内块级元素在块级元素里垂直居中同上
<div class="box box2">
<input type="text">
</div>
<b>方法二:</b>针对行级元素在块级元素里垂直居中。上述方法不好使,我这里采用行高的形式line-height: 100px;
<div class="box box3">
<a href="" title="">a标签</a>
</div>
<b>方法三:</b>有定位(absolute)的元素可以这样设: top: 50%;margin-top: -子元素高度一半;
<div class="box box4">
<span>有定位</span>
</div>
</body>
</html>
复制粘贴浏览器运行即可