各种居中问题
div 水平垂直居中
html 代码如下
html
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>已知盒子宽高
- 1、将 left right 属性都设为 50%。
- 2、计算元素位置用负 margin 的形式使 div 居中。
css
.div3 {
width: 520px;
height: 520px;
background: rgb(69, 52, 221);
left: 50%;
top: 50%;
margin-top: -260px;
margin-left: -260px;
position: absolute;
}未知盒子宽高
方法一:
- 1、采用绝对定位
- 2、把 left bottom right top 全设为 0。
- 3、margin 设为 auto
css
/*方法一: margin:auto; position: absolute; */
.div1 {
width: 520px;
height: 520px;
background: rgb(62, 184, 206);
left: 0;
bottom: 0;
right: 0;
top: 0;
margin: auto;
position: absolute;
}方法二:
- 1、将 left right 属性都设为 50%。
- 2、用 transform: translate(-50%, -50%) 把盒子移动自身的 50% 达到居中的效果。
css
.div2 {
width: 520px;
height: 520px;
background: rgb(226, 108, 220);
left: 50%;
top: 50%;
position: absolute;
transform: translate(-50%, -50%);
}
russ