侧边栏壁纸
博主头像
元 | HUB 博主等级

行动起来,活在当下

  • 累计撰写 13 篇文章
  • 累计创建 7 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

不确定宽高,div居中

元|admin
2025-07-31 / 0 评论 / 0 点赞 / 7 阅读 / 0 字

1.flex布局


<body>
    <div id="div1">
        <div id="subDiv1"></div>
    </div>
</body>
<style>
    html,body{
       height: 100%;
       width: 100%;
       margin: 0;
       padding: 0;
   }
   #div1{
     border: 1px red solid;
     height: 100%;
     width: 100%;
      /*方法一: flex布局*/
     display: flex;
     align-items: center;/*垂直居中*/
     justify-content: center;/*水平居中*/
  }
  #subDiv1{
      width: 300px;
      height: 400px;
      border: 1px solid green;
  }
</style>

2.水平垂直居中方式二:absolute定位 + transform


#div1{
    border: 1px red solid;
    height: 100%;
    width: 100%;
    position: relative;
}
#subDiv1{
   width: 300px;
   height: 400px;
   border: 1px solid green;

   /*方法二:使用transform属性*/
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
}

3.绝对定位的方式


#box {
    width: 100px;
    height: 100px;
    position: relative;
}
#content {
    width: 50px;
    height: 50px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

0

评论区