css布局之居中

来源:互联网 发布:shadow web 黑暗网络 编辑:程序博客网 时间:2024/04/30 21:32

在css中,居中是很常用的事情,因为大多数人都喜欢一种对称的美。对于居中来说,有的一个属性就可以解决,有的就需要一点技巧。我在之前的一片博客里写到了绝对定位的居中,不过那只是其中的一小部分。

先来一些人畜无害,简单的居中方法。

对于水平居中来说:

一,把margin设为auto

这种方法在使用的时候,需要把margin-left和margin-right设为auto,可以实现水平居中,但是只能适用于块级元素,而且对于浮动元素和绝对定位不适用。

二,设置text-align:center

这个属性只能对一些行内元素使用,即display为inline或者inline-block的才使用。

,使用绝对定位来居中

原理是先让元素向右移动50%的距离,这个时候左边框正好在中间的位置,然后再向左移动元素宽度一般的距离,就可以使其居中。

<style type="text/css">        .box{            width:500px;            height:300px;;            margin-left:-250px;            position:relative/absolute;            left:50%;            top:50%;            background-color: #cc18b9;        }<div class="box">    </div>
,另一种使用绝对定位来居中的方法

<style type="text/css">        .box{            width:500px;            height:300px;                       position:absolute;            left:0;            top:0;            bottom:0;            right:0;            margin:auto auto;            background-color: #cc18b9;        }<div class="box">    </div>
特别需要注意的就是这个方法,如果要水平居中,需要把left和right都设置为0,然后margin-left和margin-right都设置为auto;如果需要垂直居中,可以采用同理的方法。

对于垂直居中:

一,对行级元素居中

使line-height与父级元素的height一致。

二,对块级元素居中

1,首先直接使line-height和父级的height相等。

2,然后使用display:inline|inline-block,vertical-align:midden。

.box {            width: 200px;            height: 200px;            border: 1px solid skyblue;            line-height: 200px;        }        .box2 {            width: 100px;            height: 100px;            display: inline-block;            vertical-align: middle;            background: hotpink;        }<div class="box">    <div class="box2"></div></div>
,对于父元素高度不确定的

父元素的padding-top和padding-bottom一样 。






1 0
原创粉丝点击