html - 试图与 flex 水平对齐
问题描述
我尝试创建 2 个菜单栏,但我无法水平对齐菜单按钮,因为元素的数量不一样。我尝试使用 max-witdh、flex-basis、flex-grow、flex-shrink 属性,但无法实现我想要的。
在这里你可以找到一个代码片段:
body {
background-color: black;
text-align: center;
color: white;
font-family: Arial, Helvetica, sans-serif;
}
.row{
display: flex;
flex-direction: row;
flex: 1;
width: 100%;
}
p, .myCustomButton {
border-radius: 4px;
height: 2.8em;
font-size: 1.6rem;
color: #fff;
background-color: red;
margin: 0.4rem 0.2rem;
padding: 0 1em;
flex: 1;
}
.row2 {
justify-content: flex-end;
}
.myCustomButton {
max-width: 20%;
flex: 0.1 0.1 auto;
}
<div class='row'>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
</div>
<div class='row row2'>
<p class='myCustomButton'>test</p>
</div>
我希望在每种情况下(响应式)我的自定义按钮和测试按钮之间的大小相同。我可以通过哪种方式实现这一目标?我应该寻找哪个 CSS 属性?对我来说它是 flex-basis 但我不知道如何使用它,我已经从 mozzila doc 中阅读了它的工作原理,也许我错过了一些东西
提前致谢。
解决方案
最后一个元素不适合其他元素大小的原因是因为边距。<div>
在周围添加一个额外的<p>
并告诉一个row2
不要超过 20% 的基础对我来说是诀窍:
<div class='row row2'>
<div>
<p class='myCustomButton'>test</p>
</div>
</div>
.row2 > div {
flex: 0 1 20%;
}
.row {
display: flex;
width: 100%;
}
.row > div {
flex: 1 1 20%;
}
p {
border-radius: 4px;
height: 2.8em;
font-size: 1.6rem;
color: #fff;
background-color: red;
margin: 0.4rem 0.2rem;
padding: 0 1em;
flex: 1;
}
.row2 {
justify-content: flex-end;
}
.row2 > div {
flex: 0 1 20%;
}
<div class='row'>
<div>
<p>test</p>
</div>
<div>
<p>test</p>
</div>
<div>
<p>test</p>
</div>
<div>
<p>test</p>
</div>
<div>
<p>test</p>
</div>
</div>
<div class='row row2'>
<div><p class='myCustomButton'>test</p></div>
</div>
如果可能的话,我会推荐使用 CSS 网格,这样更容易:
推荐阅读
- sql - 存储和搜索标签具有权重的标签数据的最有效方法是什么?
- php - 我的表有两个时间戳值,其余的是字符串值。我想使用 php 在 html 中显示整个表格
- mongodb - 使用猫鼬,我试图找到具有匹配 3 个不同属性的文档,我在用户中得到空数组 If 语句执行 else 部分
- c# - WPF Datagrid 某些列未选择
- html - asp:图像无法从目录路径显示
- python - 如何用br标签分割html文本
- django - 如何在 Django 管理界面中显示来自 ImageField() 的图像?
- postgresql-9.6 - 他们有什么方法可以在使用 select 语句时使用 postgresql 会话变量
- javascript - href 的 Angular 应用程序中的基本 XSS veracode 漏洞
- javascript - settimeout 并等待是否已设置超时