DOM元素居中展示
在页面开发过程中,经常遇到需要需要让元素居中展示,并且需要适应各种分辨率的情况,在此总结几种常用的写法,仅供叁考,实际情况灵活使用,不对之处还望不吝赐教。
通过定位实现
适用于水平、垂直同时居中
1、相对于整个页面
<style>
.dom-center {width: 100px; height: 32px; line-height: 32px; color: #fff; background-color: #00a6fc; text-align: center;}
</style>
<div class="dom-center" style="position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -16px;">我要居中</div>
2、相对于其它元素
<style>
.parent-dom {width: 400px; height: 200px; border: 1px solid #000000;}
.dom-center {width: 100px; height: 32px; line-height: 32px; color: #fff; background-color: #00a6fc; text-align: center;}
</style>
<div class="parent-dom" style="position: relative;">
<div class="dom-center" style="position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -16px;">我要居中</div>
</div>
通过padding实现
适用于水平居中
<style>
.parent-dom {width: 400px; height: 200px; border: 1px solid #000000;}
.dom-center {width: 100px; height: 32px; line-height: 32px; color: #fff; background-color: #00a6fc; text-align: center;}
</style>
<div class="parent-dom">
<div style="padding-left:50%; ">
<div class="dom-center" style="margin-left: -50px;">我要居中</div>
</div>
</div>
通过margin实现
适用于水平居中
<style>
.parent-dom {width: 400px; height: 200px; border: 1px solid #000000;}
.dom-center {width: 100px; height: 32px; line-height: 32px; color: #fff; background-color: #00a6fc; text-align: center;}
</style>
<div class="parent-dom">
<div class="dom-center" style="margin: 0 auto;">我要居中</div>
</div>
文字居中实现
使用text-align,line-height可以分别实现水平,垂直居中
<div style="width: 400px; height: 200px; border: 1px solid #000000; text-align: center; line-height: 200px;">
我要居中
</div>