css | flex常见面试题

废话不多说!

#flex-内容宽度等分

1
2
3
4
5
6
7
8
9
//css
.box {
display: flex;
}

.box div {
flex: 1;
border: 1px solid red;
}
1
2
3
4
5
6
//html
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
</div>

img

#左右布局,一侧定宽,一侧自适应撑满

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//css
html,
body {
height: 100%
}

.main {
display: flex;
height: 100%;
}

.left,
.right {
height: 100%;
border: 1px solid red;
box-sizing: border-box;
}

.left {
width: 300px;
}

.right {
width: 100%;
}
1
2
3
4
5
//html
<div class="main">
<div class="left">固定宽度300px</div>
<div class="right">自适应宽度</div>
</div>

img

#未知高宽上下左右居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//css
html,
body {
height: 100%
}

.main {
display: flex;
height: 100%;
justify-content: center;
align-items: center
}

.box {
width: 300px;
border: 1px solid red;
}
1
2
3
4
//html
<div class="main">
<div class="box">未知高度上下左右居中</div>
</div>

img