css水平垂直居中方式?

一、设置margin:auto;

1 <div class="external">
2     <div class="inside"></div>
3 </div>

      使用 margin: auto; 元素仅会水平居中,并不会进行垂直居中。此时需要设置元素的 position 为 absolute,父级元素的 position 为 relative,同时元素的上下左右都需要设置为 0。

 1 .external {
 2     position: relative;
 3     width: 400px;
 4     height: 60px;
 5     background: #fff;
 6 }
 7  .inside {
 8     position: absolute;
 9     top: 0;
10     right: 0;
11     bottom: 0;
12     left: 0;
13     width: 40px;
14     height: 20px;
15     margin: auto;
16     background: red;
17 }

二、弹性布局:display: flex; 

 1 .external {
 2     display: flex;
 3     justify-content: center;
 4     align-items: center;
 5     width: 400px;
 6     height: 60px;
 7     background: #fff;
 8 }
 9 .inside {
10     width: 40px;
11     height: 20px;
12     background: red;
13 }

 三、设置position: absolute;

1 .external {
2     position: relative;
3     width: 400px;
4     height: 60px;
5     background: #fff;
6 }

       当知道元素宽度和高度时,可以设置margin-top和margin-left为负的宽高的一半。

 1 inside {
 2     position: absolute;
 3     top: 50%;
 4     left: 50%;
 5     width: 40px;
 6     height: 20px;
 7     margin-top: -10px;
 8     margin-left: -20px;
 9     background: red;
10 }

      当知道元素宽度和高度时,也可以利用calc计算设置topleft。

1 .inside {
2     position: absolute;
3     top: calc(50% - 10px);
4     left: calc(50% - 20px);
5     width: 40px;
6     height: 20px;
7     background: red;
8 }

   当未知元素宽度和高度时,可以设置position: absolutetransform: translate(-50%, -50%)。

1 .inside {
2     position: absolute;
3     top: 50%;
4     left: 50%;
5     width: 40px;
6     height: 20px;
7     background: red;
8     transform: translate(-50%, -50%)
9 }

四、设置水平对齐和行高

      通过设置text-align 和 line-height 实现单行文本水平垂直居中。

      

1 <div class="external">
2     <div class="inside">水平居中</div>
3 </div>
1 .external {
2     width: 400px;
3     height: 60px;
4     background: #fff;
5 }
6 .inside {
7     line-height: 60px;
8     text-align: center;
9 }

五、设置grid(兼容性不太好,不推荐)

1 <div class="external">
2     <div class="inside">水平居中</div>
3 </div>

  设置justify-selfalign-self或者margin: auto

 1 .external {
 2     display: grid;
 3     width: 400px;
 4     height: 60px;
 5     background: #fff;
 6 }
 7 .inside {
 8     justify-self: center;
 9     align-self: center;
10     // margin: auto;
11 }

  设置justify-itemsalign-itemsjustify-contentalign-content

1 .external {
2     display: grid;
3     justify-content: center;
4     align-items: center;
5     width: 400px;
6     height: 60px;
7     background: #fff;
8 }

六、设置table-cell

 1 .external {
 2     display: table-cell;
 3     text-align: center;
 4     vertical-align: middle;
 5     width: 400px;
 6     height: 60px;
 7     background: #fff;
 8 }
 9 .inside {
10     display: inline-block;
11 }

 

posted @ 2022-08-18 14:02  蓝色的矢车菊  阅读(62)  评论(0编辑  收藏  举报