来自IFE2015 task1
- 用两种方法来实现一个背景色为
红色
、宽度为960px
的<DIV>
在浏览器中居中
#box1{
clear:both;
width:960px;
background:red;
margin:0 auto;
}
第二种方法我选择position,将block元素移动到窗口中间。
这里先把div定位到最左边,然后把block元素的左侧移动中间,然后再把整个元素往右移动到居中
大体上如图所示
从2到3,由于是定长的block,因此可以采取左移480px
margin-left:-480px;
或者左移半个block长度。
position:relative;
left:-50%;
而1-2需要使用position移动,所以对于后者的position:relative移动方式,需要至少一个父标签,一个子标签。前者则可以在一个class内解决
<div class="centerbox">
<div id="box2">方法2bbbbbbbbbbbbbbbb</div>
</div>
<div id="box3">方法3cccccccccccccccccc</div>
.centerbox{
width:960px;
position:relative;
left:50%;
}
#box2{
background:red;
position:relative;
left:-50%;
}
#box3{
width:960px;
background:red;
position:absolute;
left:50%;
margin-left:-480px;
}
这两种方法实际上差别不大。
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
看起来都可以居中,但是实际上,在运行的时候,却产生了差异。
当窗口较大时,没什么问题:
但是窗口缩小后,却产生了差异
研究了一下大概有点想法
因为margin auto,auto不能产生负值,所以最低是auto=0,窗口大小小于定长的时候,auto取0
然后右侧被遮挡。
而position方法比较固定。向左侧移动的时候,margin-left:-480px这个比较好理解,将会移动到负值区域,被窗口遮挡。
要注意的是left:50%这样的移动语句也是强行移动到负值。