菜鸟看前端(div水平垂直居中)

编程入门 行业动态 更新时间:2024-10-10 02:17:11

<a href=https://www.elefans.com/category/jswz/34/1769734.html style=菜鸟看前端(div水平垂直居中)"/>

菜鸟看前端(div水平垂直居中)

直接上干货

基础div样式
*{margin: 0;padding: 0;}html,body{width: 100%;height: 100%;overflow: hidden;}#box{width: 100px;height: 100px;text-align: center;color: aliceblue;background: #0088dd;}
已知div宽度和高度
body{
position: relative;
}#box{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
不需要已知宽高,但必须有宽高
body{
position: relative;
}
#box{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
} 
不需要固定宽高
body{
position: relative;
}
#box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
不需要定位给父级弹性盒子
body{
display: flex;
justify-content: center;
align-items: center;
}
不需要定位给父级弹性盒子2
body{
display: flex;
}
#box{
margin: auto;
}
js实现(需要给父级一个相对定位)
    let HTML = document.documentElement;let winWidth = HTML.clientWidth;let winHeight = HTML.clientHeight;let boxW = box.offsetWidthlet boxH = box.offsetHeightbox.style.position = "absolute"box.style.left = (winWidth-boxW)/2 + 'px';box.style.top = (winHeight-boxH)/2 + 'px';

更多推荐

菜鸟看前端(div水平垂直居中)

本文发布于:2024-03-06 15:40:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1715704.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:菜鸟   水平   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!