css元素水平垂直居中的方法

1.行内块水平垂直居中

  .nav {
      width: 500px;
      height: 400px;
      line-height: 400px;
      background-color: #ccc;
      border: 1px solid #000;
      text-align: center;
  }
  
  .nav i {
      display: inline-block;
      width: 100px;
      height: 100px;
      background-color: blue;
      /* 行内块的垂直居中,父元素的高度和行高一致,给行内块设置vertical-align: middle; */
      vertical-align: middle;
  }
  
  
  
  
  

2.定位(1)

  .father {
      position: relative;
      width: 800px;
      height: 400px;
      background-color: #ccc;
      margin: 0 auto;
     
  }
  .son {
      position: absolute;
      left: 50%;
      margin-left: -50px;
      top: 50%;
      margin-top: -50px;
      width: 100px;
      height: 100px;
      background-color: #f00;
      
     或者 transform: translate(-50%, -50%);
     
  }

3.定位(2)

 .father {
     position: relative;
     width: 800px;
     height: 400px;
     background-color: #ccc;
     margin: 0 auto;
 }
 .son {
     position: absolute;
     left: 0;
     right: 0;
     top: 0;
     bottom: 0;
     margin: auto;
     /* 这种方法子元素必须设置了宽高 */
     width: 100px;
     height: 100px;
     background-color: #f00;
    
 }

4.弹性盒子flex

  .container {
      width: 300px;
      height: 300px;
      background-color: pink;
      display: flex;
      /* 主轴对齐 */
      /* 侧轴对齐 */
      justify-content: center;
      align-items: center;
  }
  /* 
     现在这个span可以设置宽高吗?
     答案是能
     弹性容器中  独立的文档流区域 规则是自定义的 弹性容器中的子
     是没有传统的块级元素和行内元素的说法的
   */
  .container span {
      width: 100px;
      height: 100px;
      border: 1px solid #ccc;
      display: flex;
      justify-content: center;
      align-items: center;

你可能感兴趣的:(html,css)