div 居中方法汇总

简介: 居中问题无论在工作还是在面试中, 都是很常见的下面我来给大家总结几种常用的方法, 大家可根据实际情况选择好了, 废话不多说, 先看下效果法1定位+偏移 (margin)html css.

居中问题无论在工作还是在面试中, 都是很常见的
下面我来给大家总结几种常用的方法, 大家可根据实际情况选择
好了, 废话不多说, 先看下效果


法1

定位+偏移 (margin)

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    position: relative;
    width: 1000px;
    height: 600px;
    background: lightblue;
}
.son {
    position: absolute;
    width: 100px;
    height: 100px;
    background: yellow;
    top: 50%;
    margin-top: -50px; /* 高度的一半 */
    left: 50%;
    margin-left: -50px; /* 宽度的一半 */
}

法2

定位+偏移 (transform)

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    position: relative;
    width: 1000px;
    height: 600px;
    background: lightblue;
}
.son {
    position: absolute;
    width: 100px;
    height: 100px;
    background: yellow;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

法3

利用 margin: auto; 自动分配多余空间

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    position: relative;
    width: 1000px;
    height: 600px;
    background: lightblue;
}
.son {
    position: absolute;
    width: 100px;
    height: 100px;
    background: yellow;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

top、left、right、bottom 的值相等即可,不一定要都是0

法4

Flex 布局

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    width: 1000px;
    height: 600px;
    background: lightblue;
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
}
.son {
    width: 100px;
    height: 100px;
    background: yellow;
}

法5

text-align: center; + vertical-align: middle;

  • html
<div class="father">
    <div class="son"></div>
    <div class="daughter"></div>
</div>
  • css
.father {
    width: 1000px;
    height: 600px;
    background: lightblue;
    text-align: center;
}
.son {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: yellow;
    vertical-align: middle;
}
.daughter {
    display: inline-block;
    width: 0;
    height: 100%;
    vertical-align: middle;
}

暂时想到这么多, 还有其他方法的小伙伴们欢迎补充, 我会将你的名字写上去, 谢谢!

相关文章
|
5月前
div盒子垂直居中的3种方法
div盒子垂直居中的3种方法
49 2
|
前端开发
div文字居中
div文字居中
div盒子水平垂直居中以及表格的居中的方法
div盒子水平垂直居中以及表格的居中的方法
142 0
让里面的DIV上下左右居中在外面的DIV里
让里面的DIV上下左右居中在外面的DIV里
59 0
div盒子水平垂直居中方法
文章转载自:div盒子水平垂直居中的方法 - 雪明瑶 这个问题比较老,方法比较多,各有优劣,着情使用。 一、盒子没有固定的宽和高 方案1、Transforms 变形 这是最简单的方法,不仅能实现绝对居中同样的效果,也支持联合可变高度方式使用。
1837 0
|
前端开发 容器
DIV垂直居中对齐
效果图: CSS: #container{ display:table-cell; width:300px; height:300px; vertical-align:middle; bo...
989 0