CSS实现水平居中的几种方法

一、对于行内元素

 1、text-aligin实现水平居中

    text-aligin:center 

 

二、对于确定宽度的块级元素

 2、margin实现水平居中

   margin:0 auto 

 3、绝对定位absolute和margin-left实现水平居中

1 .one {
2             width: 400px;
3             position: absolute;
4             margin-left: -200px;//该元素宽度的一半
5         }

 

三、对于未知宽度的块级元素

 4、CSS3通过flex实现水平居中

 1 <style>
 2         .big {
 3             display: flex;
 4             flex-direction: column;//父元素
 5         }
 6         .one {
 7            align-self: center;//子元素
 8         }
 9  </style>
10 <body>
11     <div class="big">
12         <div class="one">子元素</div>
13     </div>
14 </body>

 

5、要居中的元素设置table标签配合margin左右auto实现

 1 <style>
 2         .big {
 3             width: 900px;
 4             height: 300px;
 5             background-color: #d72e2e;
 6         }
 7         .one {
 8             width: 100px;
 9             height: 100px;
10             background-color: bisque;
11             display: table;
12             margin-left:auto;
13             margin-right: auto;
14         }
15 </style>
16 <body>
17     <div class="big">
18         <div class="one">子元素</div>
19     </div>
20 </body>

 

 

  

 

posted @ 2021-10-12 21:06  打遍天下吴敌手  阅读(2154)  评论(0编辑  收藏  举报