css元素水平垂直居中

页面结构

vertical-align: middle;针对行内块元素使用 , 如 input 对齐, img 去掉下边空白,

<body>
  <div class="box">
    <div class="wrapper">hehe</div>
  </div>
</body>

行内元素
父设置text-align:center;实现水平居中,元素设置行高line-height: 500px;垂直居中.

/* 父元素设置line-height 可以让文本之类的垂直居中 */
  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: rgb(108, 202, 209);
      text-align: center;
      line-height: 500px;
    }
    .wrapper {
      background-color: rebeccapurple;
      display: inline;
      border:1px solid red;
    }
  </style>

/* 子元素行高等于父元素高度 */
  <style>
      .box {
        width: 500px;
        height: 500px;
        background-color: rgb(108, 202, 209);
        text-align: center;
      }
      .wrapper {
        line-height: 500px;
        background-color: rebeccapurple;
        display: inline;
        border:1px solid red;
      }
    </style>

块级元素
1 绝对定位 + transform

  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: rgb(108, 202, 209);
      position: relative;
    }

    .wrapper {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: rebeccapurple;
      display: block;
      border: 1px solid red;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
    }
  </style>

2 flex布局,推荐

  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: rgb(108, 202, 209);
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .wrapper {
      width: 100px;
      height: 100px;
      background-color: rebeccapurple;
      display: block;
      border: 1px solid red;
    }
  </style>

3 display: table-cell;

  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: rgb(108, 202, 209);
      display: table-cell;
      text-align: center;	 /* 行内块元素用这个 */
		  vertical-align: middle;
    }

    .wrapper {
      width: 100px;
      height: 100px;
      background-color: rebeccapurple;
      /* display: block; */
      display: inline-block;
      /* margin: 0 auto; 块级元素 要同这个 */
      border: 1px solid red;
    }
  </style>

margin:0 auto;水平居中,要设置宽度


  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: rgb(108, 202, 209);
    }

    .wrapper {
      width: 100px;
      height: 100px;
      background-color: rebeccapurple;
      display: block;
      border: 1px solid red;
      margin: 0 auto;
    }
  </style>

行内块元素

  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: rgb(108, 202, 209);
      text-align: center;
      line-height: 500px;
    }
    .wrapper {
      width: 100px;
      height: 100px;
      background-color: rebeccapurple;
      display: inline-block;
      border:1px solid red;
      line-height: 100px; /* 让盒子下来 */
    }
  </style>
发布了25 篇原创文章 · 获赞 5 · 访问量 1140

猜你喜欢

转载自blog.csdn.net/tinfengyee/article/details/98957690