DIV+CSS垂直居中一个浮动元素


场景:在一个固定高度的div中,有一个浮动的元素,需要将这个浮动元素垂直居中。

原始代码如下:


复制代码
代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.wrapper{
width: 400px;
height: 300px;
background-color: #1f8dd6;
}
button{
float: right;
display: inline-block;
height: 50px;
width: 100px;
line-height: 50px;
}
</style>
</head>
<body>
<div class="wrapper">
<button>float right.</button>
</div>
</body>
</html>

现在只是简单的设置这个button浮动,实现的效果看起来就像这样:

现在需要将这个button在整个div里垂直居中。我的做法是在这个button外层加一个span,并且浮动这个span元素而不是之前的button。另外需要设置这个span的高和行高与外层div相同。


复制代码
代码如下:

span{
float: right;
height: 300px;
line-height: 300px;
}

现在应该就变成这样了:

完整代码:


复制代码
代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.wrapper{
width: 400px;
height: 300px;
background-color: #1f8dd6;
}
span{
float: right;
height: 300px;
line-height: 300px;
}
button{
float: right;
display: inline-block;
height: 50px;
width: 100px;
line-height: 50px;
}
</style>
</head>
<body>
<div class="wrapper">
<span>
<button>float right.</button>
</span>
</div>
</body>
</html>


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3