标签:style blog io ar color os 使用 sp strong
1、这种方法主要使用margin: auto配合元素的width来实现水平居中的效果
<div class="horizontal">content</div>
.horizontal { width: 200px; margin: 0 auto; }
(备注:因为不设置宽度的话,块级元素默认的宽度为父元素的宽度,子元素和父元素一样宽,那就没有水平居中而言啦)
使用上面方法实现元素水平居中一定要让元素满足两个条件:其一,元素需要有一个固定宽度值;其二元素的margin-left和margin-right都必须设置为auto,这两个条件少了任何一个都无法让元素达到水平居中的效果。
2、实现固定宽度的水平居中,我们还可以使用绝对定位配合负的margin来实现
<div class="horizontal">content</div> .horizontal { width: 960px; position: absolute; left: 50%; margin-left: -480px;/*此值等于“-width/2”*/ }
这种方法有几点需要注意:其一要有一个固定宽度,其二对要居中的元素进行绝对定位,并且“left: 50%”;其三对此元素设置一个负的“margin-left”并且值等于宽度的一半,另外如果元素不是相对于浏览器的话,还需要在其父元素上设置一个相对定位“position: relative”。
3、这种方法主要是针对单行文本居中或者前面介绍的table格式居,主要运用的是text-align:center让元素水平居中
.testH{text-align:center;}
标签:style blog io ar color os 使用 sp strong
原文地址:http://www.cnblogs.com/lxf1117/p/4131702.html