欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

div元素如何实现完美垂直居中?试试这些方法!

最编程 2024-08-08 19:15:19
...

如何用让嵌套在里面的div居中

本人是一个前端新手,如何让两个相互嵌套的div,让里面的div居中是一个比较简单的问题,面试也常问,我就从其他博客中提取稍微总结一下(转载侵删),也加了一点自己的困惑和理解,错误的地方希望能有人指出:

  • 利用position:absolute的特性
  • 设置margin为auto
  • display:table-cell
  • transform
  • flex

效果图

方法一:利用position:absolute的特性

先设置元素的top、left偏离50%,再用margin让位置往回一半。

.parent{
    width: 400px;
    height: 400px;
    position: relative;
    background: red;
}
.child{
    width: 200px;
    height: 200px;
    position: absolute;
    background: green;
    top: 50%;
    bottom: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

需要注意的是要将父级的postision设为relative,否则元素将不会相对于父级进行定位
该方法在pc中的兼容性很好,另外,稍微改一下,也就是:

.parent{
    width: 400px;
    height: 400px;
    position: relative;
    background: red;
}
.child{
    width: 200px;
    height: 200px;
    position: absolute;
    background: green;
    top: 50%;
    margin-top: -100px;
}

就可以让div只在垂直方向居中,还是比较常用的
这里写图片描述

方法二:设置margin为auto

.parent{
    width: 400px;
    height: 400px;
    position: relative;
    background: red;
}
.child{
    width: 200px;
    height: 200px;
    position: absolute;
    background: green;
    margin: auto;
    top: 0;
    right:0;
    bottom: 0;
    top: 0;
}

兼容性:主流浏览器都支持,IE6不支持

方法三:display:table-cell

.parent{
    width: 400px;
    height: 400px;
    background: red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.child{
    width: 200px;
    height: 200px;
    background: green;
    display: inline-block;
    vertical-align: middle;
}

table-cell属性是让标签元素以表格单元格的形式呈现,类似于td标签
vertical-align是行内元素的一个属性,设置行内元素是以基线对齐还是中间对齐
text-align设置后让元素在水平方位居中
兼容性:由于table-cell是css3的属性,兼容性上低版本的IE不支持该属性

方法四:transform

.parent{
    width: 400px;
    height: 400px;
    background: red;
    position: relative;
}
.child{
    width: 200px;
    height: 200px;
    background: green;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

这边我有点不太理解的是,我发现并不需要设置position:absolute直接用translate(50%, 50%)也能垂直居中,但网上多数方法都用了position:absolute,希望有大神能够替我解答下我的疑问
兼容性:IE9以下不支持transform,手机端上的支持比较好

方法五: flex

.parent{
    width: 400px;
    height: 400px;
    background: red;
    display: flex;
    align-items: center;
    justify-content: center;
}
.child{
    width: 200px;
    height: 200px;
    background: green;
}

flex在移动端的支持非常好,在pc端的兼容性还是差了点,所以这种方式是移动端的首选

转载自:https://www.cnblogs.com/libin-1/p/5869430.html