对于页面上的块级元素,只须定宽及设置margin:auto 0;即可在垂直上居中,但对于浮动的元素垂直居中是无效的。那么我们如何来处理这个问题呢,今天我们来探讨下。
场景:在一个固定高度的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>
|