div的居中

1.讲解:

外层div设置text-align:center只对文本元素起作用,对div不起作用

内层div设置style="margin:0 auto;"则可以让内层div居中显示

2.代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style>
        .red {border:1px solid red;}
        .green {border:1px solid green;}
        .hw200 {
            width:200px;
            height:200px;
        }
    </style>
</head>
<body>
    <div style="text-align:center">
        <span class="green">这是一个文本</span>
    </div>
     <div style="text-align:center">
        <div class="red hw200">这是一个div</div>
    </div>
    <div style="">
        <span class="green">这是一个文本</span>
        <div class="red hw200" style="margin:0 auto;">这是一个div</div>
    </div>
    <div style="text-align:center">
        <span class="green">这是一个文本</span>
        <div class="red hw200" style="margin:0 auto;">这是一个div</div>
    </div>
</body>
</html>

3.效果图:


发布了42 篇原创文章 · 获赞 25 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq812858143/article/details/50776981