【text-align】如何对div元素起作用

父元素:text-align:center;

div子元素:marign:0px auto;


通过在当前元素使用margin:0px auto可以实现当前元素在父元素中的水平居中效果。


通常情况下text-align:center是用作将文本水平居中的,如果让一个div水平居中,一般要使用margin:0px auto这段代码,这个对于有开发经验的前端人员没有任何问题,但初学者往往会出现使用text-align:center来实现div水平居中的情况,并且还会得出这样的结论:有的浏览器可以有的浏览器不可以。下面就看一段代码实例:
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>为什么text-align:center无法将div水平居中-蚂蚁部落</title> 
<style type="text/css">
div{
  width:200px;
  height:200px;
  background-color:green;
  text-align:center;
}
#children{
  width:100px;
  height:100px;
  background-color:red;
}
</style>
</head>
<body>
<div style="text-align:center;">
<div id="children"></div>
</div>
</body>
</html>
 以上代码的初衷是想让子元素在父元素中水平居中,这个在IE7和IE7以下浏览器中是可以的,但是在IE8和和IE8以浏览器或者其他标准浏览器中是没有任何效果的。text-align:center一般是用来规定文本和内联元素的水平居中对齐,如果想要让块级水平居中对齐,一般使用margin:0px auto来实现,代码实例如下:
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>为什么text-align:center无法将div水平居中-蚂蚁部落</title> 
<style type="text/css">
div{
  width:200px;
  height:200px;
  background-color:green;
}
#children{
  width:100px;
  height:100px;
  background-color:red;
  margin:0px auto;
}
</style>
</head>
<body>
<div style="text-align:center;">
<div id="children"></div>
</div>
</body>
</html>
 以上代码通过在当前元素使用margin:0px auto可以实现当前元素在父元素中的水平居中效果。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值