css盒子水平居中的方案

1、定位:3种

(1)百分比,知道具体宽高
.box{   //让盒子距离左上50%,然后向左上移动一半的距离
    position: absolute;
    top:50%;
    left:50%;
    margin-top: -50px;
    margin-left: -50px; 
}
(2)自动,不知道具体宽高
.box{   //不需要具体宽高,margin自动填充剩余的空间
    position: absolute;
    top:0;
    left:0;
    bottom: 0; 
    right: 0;
    margin: auto;
}
(3)transform, translate, 不需要宽高
.box{   //不需要宽高,translate(-50%,-50%)元素在水平方向和垂直方向同时移动,兼容性不好
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
}

2、display:flex

给父节点设置flex盒子,并让他的子元素主轴交叉轴居中,不兼容,移动端常用

body {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

3、JS-dom

获得父级和盒子元素的宽高,让盒子绝对定位,并使其距离左上位置为剩余空间的一半

  let html = document.documentElement,   //返回html dom中的root根节点 即'< html>'
  winW = html.clientWidth,	         //获取当前屏幕的宽度和高度
  winH = html.clientHeight,
  box = document.getElementById("box"),  //获取盒子的宽度和高度
  boxW = box.offsetWidth,	
  boxH = box.offsetHeight;
  box.style.position="absolute";
  box.style.left = (winW-boxW)/2+"px";
  box.style.top = (winH-boxH)/2+"px";
posted @   Ericup  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示