CSS让元素居中布局

水平居中

这里写图片描述

HTML:css

<div class="wrapper">
    <div class="item"></div>
</div>

CSS:css3

div.wrapper { height: 500px; width: 1000px; border: 1px solid #000; }
div.item { margin: 0 auto; height: 200px; width: 200px; background-color: gray; }

元素高度和高度已知,水平和垂直都居中

这里写图片描述

HTML:markdown

<div class="wrapper">
    <div class="item"></div>
</div>

CSS:app

div.wrapper { height: 500px; width: 1000px; border: 1px solid #000; }
div.item { position: relative; top: 50%; left: 50%; height: 200px; width: 200px; margin-left: -100px; margin-top: -100px; background-color: gray; }

居中原理:spa

这里写图片描述

先利用定位使得元素的左上角在父元素的中间(水平和垂直),top、left设置为50%是根据父元素计算,注意,当是绝对定位时,是根据最近position设置为relative或者absolute的元素计算。code

因此,设置成绝对定位须要在父元素加上:position: relative; 否则这里会根据最近的(body)计算orm

div.wrapper { position: relative; height: 500px; width: 1000px; border: 1px solid #000; }

元素高度和高度未知,水平和垂直都居中

这里写图片描述

HTML:xml

<div class="wrapper">
    <div class="item"></div>
</div>

CSS:图片

div.wrapper { height: 500px; width: 1000px; border: 1px solid #000; }
div.item { position: relative; top: 50%; left: 50%; height: 200px; width: 200px; transform: translate(-50%, -50%); background-color: gray; }

居中原理:ip

这里写图片描述

这里利用了CSS3的移动——transform: translate

先利用定位使得元素的左上角在父元素的中间(水平和垂直),而后使用css3的偏移使元素向上、向左移动50%(这里的50%是根据本身的宽度和高度),和margin不一样,margin若是为百分比是根据父元素计算。

仍然,设置成绝对定位仍然须要在父元素加上:position: relative;

由于须要用到css3的知识,因此兼容性为:

IE9+ 、Chrome4.0+、FF3.5+、Safari3.1+、Opera10.5+

不肯定数目子元素居中

标题可能很差理解,直接上想要效果图:

图中是个居中的分页器,因为页数可能改变,明显宽度不肯定,若是用CSS3的偏移能够解决,可是有兼容性问题,这里就不介绍,参考上面的方法。

这里写图片描述

下面介绍另外一种办法:

HTML:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

CSS:

ul { position: relative; float: left; left: 50%; }
li { float: left; position: relative; left: -50%; width: 30px; height: 30px; line-height: 30px; margin-left: 5px; list-style: none; text-align: center; background-color: gray; color: #fff; }

这里写图片描述

如上图,首先ul和li都是float:left,这时,ul的实际宽度是根据li的个数改变而改变的。

而后给ul设置为相对定位,而且left设置为50%。效果如图的蓝色部分,ul的左边在父元素的中间(50%)

这时li也设置为相对定位,left设置为-50%,这时是根据父元素,也就是ul来计算,全部的li都偏移ul宽度的一半,这样就居中了!

相关文章
相关标签/搜索