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

水平居中

1.text-align

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

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

  • css代码

  • html代码

    
水平居中-

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

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

  • css代码

  • html代码

    
水平居中-

垂直居中

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代码

    
垂直居中

你可能感兴趣的:(css水平居中&垂直居中的几种方法)