【青训营】做面试题般回顾前端基础知识CSS篇 – 4 弹性布局与经典面试题CSS实现垂直居中

本文来研究一下弹性布局 顺带着把CSS垂直居中的问题解决下~

另外 这个主题好好看啊??

1.弹性布局学习

先来学习下CSS3中的概念——弹性盒子

image.png

为了实现弹性布局 我们在容器上加上display:flex;属性——

image.png

弹性布局是很灵活的!

image.png
以及这种方式 (更加灵活)

image.png

下面就是我们今天讨论的面试题的主角——

image.png

  • 另外justify-content属性用于设置子元素在主轴上的对齐

2.经典面试题

如何实现元素的垂直、水平居中?

本回答的前提(初始代码):

如下——父盒子套着子盒子

    <style>
        .father{
            display: flex;
            background-color: pink;
            width: 800px;
            height: 400px;
        }
        .son{
            background-color: plum;
            width: 200px;
            height: 100px;
        }
    </style>
    <div class="father">
        <div class="son">
            我是类似行内块元素的子元素 (可以设置宽高且不换行)
        </div>
    </div>
复制代码

经过下面的几种方式设置垂直、水平居中后

效果如下
image.png

简单来说分三种——

  • flex布局

  • 绝对定位(如果要限制在父盒子里就给父盒子加个相对定位)

  • grid布局 table-cell布局

首先来看看如何使用今天的今日主角——flex布局

1.利用flex中的属性设置父元素

只放起作用的那些属性了~ 下面同理

.father{
    display: flex;
    justify-content: center;/* 水平居中 */
    align-items: center;/* 垂直居中 */
}
复制代码

另外垂直居中还可以通过 align-self:center; 来实现

2.父元素设置flex布局 子元素设置margin:auto

.father{
    display:flex;
}
.son{
    margin: auto;
}
复制代码

这里蛮有意思的 如果不在弹性布局中 margin:auto;只能做到水平居中

这其中的道理可以看这篇文章了解一下(具体就是与auto的定义有关)

接下来看两个利用定位达成效果的方法

3.子绝父相+子元素设置margin

.father{
    position: relative;
}
.son{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}
复制代码

4.子绝父相+子元素通过transform向左上偏移

.father{
    position: relative;
}
.son{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
复制代码

这里我记得在初学CSS的时候就学习过hhh 回忆了一下!

来看另外两种布局方式的实现——

  • grid
  • table-cell

5.父元素使用grid布局 子元素设置margin:auto

.father{
    display: grid;
}
.son{
    margin: auto;
}
复制代码

6.父元素使用table-cell布局 子元素设置成行内块元素

.father{
    display: table-cell;
    text-align: center;/* 水平居中 */
    vertical-align: middle;/* 垂直居中 */
}
.son{
    display: inline-block;
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享