上又要到秋招的时候了,又有不少人打算换工作了。前端在面试中总会被问到的一道基础题div居中方法,这里给大家总结一下都有哪些常用的方法。
还未偏移一半自身宽高
<style>
.parent {
position: relative;
width: 500px;
height: 500px;
border: solid red 1px;
}
.demo {
position: absolute;
width: 100px;
height: 100px;
border: solid blue 1px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<body>
<div class="parent">
<div class="demo"></div>
</div>
</body>
通过flex弹性布局设置垂直居中和水平居中
<style>
.parent {
width: 500px;
height: 500px;
border: solid red 1px;
display: flex;
// 垂直,水平居中
align-items: center;
justify-content: center;
}
.demo {
width: 100px;
height: 100px;
border: solid blue 1px;
}
</style>
<body>
<div class="parent">
<div class="demo"></div>
</div>
</body>
在子元素不知道自身宽高情况,使用transform进行比偏移。
<style>
.parent {
position: relative;
width: 500px;
height: 500px;
border: solid red 1px;
}
.demo {
position: absolute;
border: solid blue 1px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent">
<div class="demo">居中</div>
</div>
</body>
以上3种是常用的方法,当然还有其他居中方法比如grid布局,table-cell布局等。
. 元素高度声明的情况下在父容器中居中:绝对居中法
<div class="parent">
<div class="absolute-center"></div>
</div>
.parent {
position: relative;
}
.absolute-center {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 70%;
width: 70%;
}
优点:
1.跨浏览器,包括 IE8-10
2.无需其他冗余标记,CSS 代码量少
3.完美支持图片居中
4.宽度高度可变,可用百分比
缺点:
1.必须声明高度
2. 负外边距:当元素宽度高度为固定值时。设置 margin-top/margin-left 为宽度高度一 半的相反数,top:50%;left:50%
<div class="parent">
<div class="negative-margin-center"></div>
</div>
.parent {
position: relative;
}
.negative-margin-center {
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
height: 300px;
width: 300px;
}
优点:
良好的跨浏览器特性,兼容 IE6-7
代码量少
缺点:
不能自适应,不支持百分比尺寸和 min-/max-属性设置
内容可能溢出容器
边距大小域与 padding,box-sizing 有关
3. CSS3 Transform 居中:
<div class="parent">
<div class="transform-center"></div>
</div>
.parent {
position: relative;
}
.transform-center {
position: absolute;
left: 50%;
top: 50%;
margin: auto;
width: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
优点:
内容高度可变
代码量少
缺点:
IE8 不支持
属性需要浏览器厂商前缀
可能干扰其他 transform 效果
4. table-cell 居中:
法一
#wrap{ position:absolute; width:300px; height:200px; top:50%; left:50%; transform:translate(-50%,-50%) ; background:#009688; } 若是下面的代码,其结果就是错误的
#wrap{ width:300px; height:200px; margin-top:50%; margin-left:50%; transform:translate(-50%,-50%) ; background:#009688; }
原因:
当margin设置成百分数的时候,其top right bottom left的值是参照父元素盒子的宽度进行计算
方法二
直接用弹性盒布局,作用于父元素上实现
*请认真填写需求信息,我们会在24小时内与您取得联系。