css水平居中&垂直居中的几种方法

水平居中

1.text-align

  • text-align 文本居中:在父级标签上设置,内部的子元素不管是块级元素 或 非块级元素,都可以使其中的文本水平居中;但需注意块级元素会占用整行的宽度,文本是在这个宽度中作水平居中。
  • 区块中文本居中,同时能使成分为"行内元素或行块元素"的子元素整块居中。
    • html代码
    <div class="wrap">
        <span class="box">水平居中-</span>
    </div>
  • css代码
         .wrap{
             height: 50px;
             border: 1px solid red;
             text-align: center;
         }
         .box{
             /* display: inline-block;
             width: 200px; */
             border: 1px solid blue;
         }

2.margin:0 auto;

  • margin:0 auto;元素居中:整个区块元素水平居中,只能对设置了宽度的块元素产生影响
    • html代码
    <div class="wrap">
        <div class="box">水平居中-</div>
    </div>
  • css代码
         .wrap{
             height: 50px;
             border: 1px solid red;
         }
         .box{
            width: 200px;
             border: 1px solid blue;
             margin: 0 auto;
         }

3.flex布局——justify-content: center;属性

  • css代码
<style>
      .wrap {
        height: 50px;
        border: 1px solid red;
        display: flex;
        justify-content: center;
      }
      .box {
        width: 200px;
        border: 1px solid blue;
      }
    </style>
  • html代码
<body>
    <div class="wrap">
      <div class="box">水平居中-</div>
    </div>
</body>

4.position定位属性实现水平居中

绝对定位+transform,translateX可以移动本身元素的50%

  • css代码
<style>
      .wrap {
        height: 50px;
        border: 1px solid red;
        position: relative;
      }
      .box {
        width: 200px;
        border: 1px solid blue;
        position: absolute;
        /* 踩坑:注意事项('-'  前后需要空格!! */
        left: 50%;
        transform: translateX(-50%);
      }
    </style>
  • html代码
<body>
    <div class="wrap">
      <div class="box">水平居中-</div>
    </div>
</body>

垂直居中

1.设定行高(line-height)

适用于“单行”的“行内元素”(inline、inline-block),将line-height设成和高度一样的数值,内容的行内元素就会被垂直居中

.div0{
  width:200px;
  height:150px;
  border:1px solid #000;
  line-height:150px;
  text-align:center;
}
.redbox{
  display:inline-block;
  width:30px;
  height:30px;
  background:#c00;

2.使用相对定位+transform属性

.box{
    width:200px;
    height:200px;
    border:1px solid #000;
}
.item{
    position: relative;
    width:100px;
    height:50px;
    top:50%;
    transform:translateY(-50%);
    background:#095;
}

3.使用绝对定位

.box{
    position: relative;
    width:200px;
    height:150px;
    border:1px solid #000;
}
.item{
    position: absolute;
    width:100px;
    height:50px;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin:auto;
    background:#f60;
}

4.使用flex布局

  • css代码
 .wrap {
        height: 50px;
        border: 1px solid red;
        display: flex;
        align-items: center;
      }
      .box {
        width: 200px;
        border: 1px solid blue;
  • html代码
<body>
    <div class="wrap">
      <div class="box">垂直居中</div>
    </div>
</body>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容