前段时间面试时的问题,当时答得并不全面,下来自己重新整理一遍。
一、inline元素
<!DOCTYPE html> <html> <head> <title>元素垂直居中</title> </head> <body> <div class="demo"> <span>These</span> <span>elements</span> <span>will be</span> <span>centered vertically</span> </div> </body> </html>
- 设置行高与容器高度相等
<style type="text/css"> .demo { background-color: #000; height: 100px; } .demo span { background-color: #777; color: #fff; line-height: 100px; }
</style>
效果:
2. 设置上下内边距相等
<style type="text/css"> .demo { background-color: #000; padding: 50px; } .demo span { background-color: #777; color: #fff; padding: 50px 0; } </style>
效果:
3.inline元素的 CSS 属性 vertical-align,常用于 inline-level 和 table-cell 的元素。
<style type="text/css"> .demo { background-color: #000; height: 100px; display: table; } .demo span { background-color: #777; color: #fff; display: table-cell; vertical-align: middle; } </style>
效果:
二、block元素
<!DOCTYPE html> <html> <head> <title>元素垂直居中</title> <style type="text/css"> .parent { background-color: #000; height: 200px; } .child { width: 100%; height: 100px; background-color: #ccc; } </style> </head> <body> <div class="parent"> <div class="child"></div> </div> </body> </html>
1.使用绝对定位、负外边距
<style type="text/css"> .parent { position: relative; background-color: #000; width: 500px; height: 200px; } .child { position: absolute; width: 100px; height: 120px; background-color: #ccc; color: #fff; top: 50%; left: 50%; margin-top: -60px; margin-left: -50px; } </style>
效果:
2.利用绝对定位以及 transform ,适用于不知道元素的宽度盒高度。
<style type="text/css"> .parent { position: relative; background-color: #000; height: 200px; } .child { position: absolute; background-color: #ccc; width: 100px; height: 120px; top: 50%; transform: translateY(-50%); } </style>
效果:
3.CSS3 flex属性
<style type="text/css"> .parent { position: fixed; display: -webkit-flex; align-items: center; background-color: #000; height: 200px; width: 300px; } .child { background-color: #ccc; width: 100px; height: 120px; } </style>
效果: