程序员

温故而知新之CSS篇-盒子水平垂直居中的方法

作者:admin 2021-10-12 我要评论

盒子水平垂直居中的方法 1使用定位的方法三种方法 第一种方法已知盒子的宽高需要计算盒子的宽高 body div classfather div classson儿子/div /div/bodystyle .fa...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

盒子水平垂直居中的方法
(1)使用定位的方法(三种方法):
第一种方法:(已知盒子的宽高,需要计算盒子的宽高)

<body>
    <div class="father">
      <div class="son">儿子</div>
    </div>
</body>
<style>
      .father{
        position: relative;
        /* 这一步是为了让son基于father定位 */
        width: 500px;
        height:300px;
        border: 1px solid blue;  
      }
      .son{
        position: absolute;
        left: 50%;  
        top: 50%;
        /* 到这一步为止,son的左上角是在father里面垂直居中的 */
        margin-left: -100px; 
        margin-top: -50px;
        /* 这里是为了让son的中心位置在father中垂直居中,所以取了son宽高的一半。 */
        width: 200px;
        height: 100px;
        background-color: pink;
      }
    </style>

第二种方法:(盒子必须要有宽高,但是不需要计算宽高)

 .son{
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 200px;
        height: 100px;
        background-color: pink;
      }

第三种方法:(不需要知道盒子的宽高)

.son{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: pink;
      }

在这里插入图片描述

(2)使用display:flex的方法:

.father{
        display: flex;
        justify-content: center;
        /* x轴 */
        align-items: center;
        /* y轴 */
        width: 500px;
        height:300px;
        border: 1px solid blue;  
      }
      .son{
        width: 200px;
        height: 100px;
        background-color: pink;
      }

(3)使用JavaScript的方法:

<body>
    <div class="father" id="box">
      js实现垂直居中
    </div>
    <script>
      let HTML = document.documentElement;
      windowW = HTML.clientWidth;
      windowH = HTML.clientHeight;
      boxW = box.offsetWidth;
      boxH = box.offsetHeight;
      console.log(boxH)
      box.style.position = "absolute";
      box.style.left = (windowW-boxW)/2+'px';
      box.style.top = (windowH-boxH)/2+'px';
    </script>
  </body>
  <style>
  body{
        position: relative;
      }
  #box {
        width: 200px;
        height: 100px;
        background-color: pink ;
      }</style>
;原文链接:https://blog.csdn.net/weixin_49175902/article/details/116124464

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 温故而知新之CSS篇-盒子水平垂直居中的

    温故而知新之CSS篇-盒子水平垂直居中的

  • 就凭查漏补缺这点,面试字节跳动之前请

    就凭查漏补缺这点,面试字节跳动之前请

  • C语言零基础从入门到精通之—递归

    C语言零基础从入门到精通之—递归

  • HTML的一些常用的标签和部分css知识

    HTML的一些常用的标签和部分css知识

腾讯云代理商
海外云服务器