CSS:文本或图片水平居中、垂直居中的代码

2022-5-6 12:09:28 [大杂烩]

网页布局中需要将内容上下左右居中。

文本的左右居中比较容易,style中加上"text-align:center;"就可以实现。一些情况下如果指定了内容的宽度,使用"margin:0 auto;"也可以使内容居中。

上下居中比较费事,在使用table定位布局的时代,valign=middle 就可以了,但在DIV模式下,这条就没有效果,尽管可以使用 display:table、display:table-cell来模拟,毕竟不太方便。

归纳一下,实现上下垂直居中有以下几种情况:

一、容器高度固定、内容为一行文字的垂直居中:内容 line-height

使用line-height等于盒子的高度。

<div id="Box" style="height:100px;border:1px solid #333333;">

<p style="line-height:100px;">文本上下垂直居中<p>

</div>

  二、容器高度未知,内容高度固定的垂直居中:

1.容器相对定位;内容绝对定位,top:0,bottom:0,margin: auto


<div id="Box" style="position: relative; border:1px solid #333333;width:300px;height:200px;">
<p style="position: absolute; top: 0; bottom:0;height:60px;margin: auto;">文本上下<br>垂直居中<p>
</div>

上述在IE下无效。

2.容器相对定位;内容绝对定位,top:50%; margin-top: (内容高度的一半);

<div id="Box" style="position: relative; border:1px solid #333333;width:300px;height:200px;">
<p style="position: absolute;height:60px;top: 50%; margin-top: -40px;">文本上下<br>垂直居中<p>
</div>

 三、容器高度未知、,内容高度未知的垂直居中:容器相对定位;内容相对定位,top: 50%,translateY(-50%)


<div id="Box" style="position: relative; border:1px solid #333333;width:300px;height:200px;">
<p style="

    position: relative; top: 50%;
    -moz-transform: translateY(-50%); /*向上平移 自身的50%*/
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);

;">文本上下<br>垂直居中<p>
</div>




上面要求CSS3