无法使flexbox垂直对齐元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法使flexbox垂直对齐元素相关的知识,希望对你有一定的参考价值。
我刚刚开始学习html / CSS,我无法让flexbox垂直地对齐元素(或者根本不做任何事情)。我在概念上理解为什么它没有将元素识别为合理的单独元素。
CSS和HTML:
.box {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.odd-elements {
margin: auto;
width: 100px;
height: 100px;
border-top-width: 1px;
border-top-color: #687291;
border-top-style: solid;
text-align: center;
background-color: #dfe1e7;
}
.even-elements {
margin: auto;
width: 100px;
height: 100px;
border-top-width: 1px;
border-top-color: #687291;
border-top-style: solid;
text-align: center;
background-color: #eeeff2;
}
#e6 {
margin: auto;
width: 100px;
height: 100px;
border: 4px solid black;
text-align: center;
vertical-align: middle;
line-height: 100px;
background-color: #687291;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styleA.css" />
<title>CS142 Project #1</title>
</head>
<body>
<div class="box">
<span class="odd-elements">A</span>
<span class="even-elements">B</span>
<span class="odd-elements">C</span>
<span class="even-elements">D</span>
<span class="odd-elements">E</span>
<span id="e6">F</span>
</div>
</body>
</html>
答案
只需将您的CSS更改为:
.odd-elements, even-elements{
display: inline-flex;
justify-content: center;
align-items: center;
}
另一答案
如果您想将您的孩子物品居中,您必须将您的孩子用作弹性容器。在这种情况下,span标签是您的孩子。因此,您必须在span标记中添加display:flex(To do flex container),justify-content:center,align-items:center。顺便说一句,如果你在span标签中添加一个公共类,那就太好了。
.box {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.box span {
display: flex;
justify-content: center;
align-items: center;
}
.odd-elements {
margin: auto;
width: 100px;
height: 100px;
border-top-width: 1px;
border-top-color: #687291;
border-top-style: solid;
text-align: center;
background-color: #dfe1e7;
}
.even-elements {
margin: auto;
width: 100px;
height: 100px;
border-top-width: 1px;
border-top-color: #687291;
border-top-style: solid;
text-align: center;
background-color: #eeeff2;
}
#e6 {
margin: auto;
width: 100px;
height: 100px;
border: 4px solid black;
text-align: center;
vertical-align: middle;
line-height: 100px;
background-color: #687291;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styleA.css" />
<title>CS142 Project #1</title>
</head>
<body>
<div class="box">
<span class="odd-elements">A</span>
<span class="even-elements">B</span>
<span class="odd-elements">C</span>
<span class="even-elements">D</span>
<span class="odd-elements">E</span>
<span id="e6">F</span>
</div>
</body>
</html>
以上是关于无法使flexbox垂直对齐元素的主要内容,如果未能解决你的问题,请参考以下文章
无法垂直对齐文本 - angularJS + bootstrap + flexbox