如何用CSS水平、垂直居中

1. 居中文本
要居中一个块级元素的文本,用text-align属性

程序代码 程序代码
h1, h2, h3 {

text-align:center;

}

另外一种方法就是使用margins来居中,这时文本要在它的容器里

程序代码 程序代码
h1, h2, h3 {

margin-left: auto;

margin-right: auto;

}

2. 居中表格
要居中一个表格,把表格作为一个div的子元素

程序代码 程序代码
<div class="center">

<table width="50%" border="1" cellpadding="30">

<tr>

<td>This is the first cell</td>

<td>This is the second cell</td>

</tr>

<tr>

<td>This is the third cell, it's under the first cell</td>

<td>This is the fourth cell, it's under the second cell.</td>

</tr>

</table>

</div>

添加以下规则

程序代码 程序代码
.center table {

margin: 0 auto;

text-align: left;

}

3. 居中图片
如果想要居中图片的话,在img外嵌套一个div元素

程序代码 程序代码
<div class="flagicon"><img src="flag.gif" alt="Flag " width="160 "

height="60" /></div>

添加以下规则

程序代码 程序代码
.flagicon {

text-align: center;

}

如果要想以固定宽度的值居中(例如图片),首先设置父元素的padding-left为50%,然后算一下要居中的图片宽度一半的值,把这个值的负数设置为图片的margin-left即可

程序代码 程序代码
<img src="wolf.jpg" width="256" height="192" alt="Photo of wolf.">

程序代码 程序代码
body {

padding-left: 50%;

}

img {

/* equal to the negative of half its width */

margin-left: -128px;

}

4.垂直居中
CSS里没有垂直居中,使用这条规则,可以使任何元素垂直居中

程序代码 程序代码
img {

position: absolute;

top: 50%;

left: 50%;

/* 元素高度一半的负数 */

margin-top: -96px;

/* 元素宽度一半的负数 */

margin-left: -128px;

height: 192px;

width: 256px;

}

如果想要同时垂直居中图片和文字,把图片和文字放到div里

程序代码 程序代码
<div id="centerFrame">

<p>Epsum factorial non deposit quid pro quo hic escorol. Olypian

quarrels et gorilla congolium sic ad nauseum. Souvlaki ignitus

carborundum e pluribus unum. Defacto lingo est igpay atinlay.</p>

<img src="wolf.jpg" width="256" height="192" alt="Photo of

wolf." />

</div>

去掉高度属性,自己调整margin-top并使其居中

程序代码 程序代码
#centerFrame {

position: absolute;

top: 50%;

left: 50%;

/* adjust negative value until content is centered */

margin-top: -150px;

margin-left: -138px;

width: 256px;

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值