HTML 和 CSS 必须知道的重点和难点

1.   怎么让一个不定宽高的 div 水平垂直居中

    1.1  使用Flex

              方法:只需要在父盒子设置: display: flex;  justify-content: center;  align-content: center; 即可,由于父盒子没有宽高,所以会通栏显示,子盒子同样没有宽高,它的大小由其内容撑开。

      演示代码如下: 

<style>
   .father {
      display: flex;
      justify-content: center;
      align-content: center;
      background: #00f;
     }
    .son {
      background: red;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="son">我是子盒子</div>
  </div>
</body>

   展示效果: 

     

   

   1.2 使用CSS3 的transform 和 定位

    方法:  给父盒子设置:  display: relative;

                 给子盒子设置: transform: translate(-50%, -50%);  position: absolute;   top: 50%;  left: 50%;   由于父盒子没有高度,所以不显示父盒子的颜色,子盒子是相对                                                于浏览器页面居中的

    代码如下: 

<style>
    .father {
      display: relative;
      background: #f00;
    }
    .son {
      transform: translate(-50%, -50%);
      position: absolute;
      top: 50%;
      left: 50%;
      background: #0f0;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="son">我是子盒子</div>
  </div>
</body>

   效果展示:    

               

                                             

     1.3 使用 display: table 

   方法: 为父盒子设置:   display: table;    暂时给父盒子一个宽高   width: 223px;   height: 166px;

              为子盒子设置: display: table-cell;  vertical-align: middle;  text-align: center;

   代码如下:    
     
<style>
    .father {
      width: 223px;
      height: 166px;
      display: table;
      background: #ff0f;
    }
    .son {
      display: table-cell;
      vertical-align: middle;
      text-align: center;
      background: #0f0;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="son">我是子hdfh dhds hdfh sf hfghtsys 盒子</div>
  </div>
</body>

 效果展示: 

                          

猜你喜欢

转载自www.cnblogs.com/lirun-rainbow/p/9697368.html