左右居中 方式一:文本在div中左右居中
<div style="text-align:center;">
这个要居中
</div>
左右居中 方式二: div在容器中居中
<div style="width:1000px;">
<div style="width:100px; margin:0 auto;">这个要居中</div>
</div>
上下居中方式一:div在容器中上下居中
<div style="width:1000px;height:600px; background-color:yellow;border:1px;margin:0;padding:0;">
<div style="width:100px; margin:0 auto; height:30px; background-color:red;position:relative; top:50%; margin-top:-15px;">这个要居中</div>
</div>
主要讲一下上面这种居中的原理,主要是通过position:relative; 让元素可以通过top、left来定位。所以我们用top定位50%,这样会因为元素自身高度让元素偏下,把我们需要用margin-top 把元素移上去一点,具体数值是当前元素高度的一半。关键代码如下
position:relative;
top:50%;
margin-top:-15px;