有谁知道如何对齐 <hr>
flex 容器内的元素。当我做 flex-start
所有其他元素对齐,除了 <hr>
.我需要一个不使用 position: absolute
的解决方案在 <hr>
上元素,因为这会影响文档流并导致其他问题。
代码笔:https://codepen.io/emilychews/pen/QaPQaW
CSS
body {margin: 0; padding: 0;}
.box {
width: 300px;
height: 300px;
background: red;
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
}
hr {
position: relative;
display: block;
background: white;
height: 3px;
width: 75px;
margin-left: 0 auto;
}
HTML
<div class="box">
<h1> Hello </h1>
<hr>
<p> Thanks </p>
</div>
最佳答案
hr
元素设置了默认边距,在 Chrome 中它设置为:
-webkit-margin-before: 0.5em;
-webkit-margin-after: 0.5em;
-webkit-margin-start: auto;
-webkit-margin-end: auto;
并且由于 Flexbox 中的自动边距会覆盖 justify-content
/align-*
属性,因此您需要将其删除,例如margin: 0;
将在这种情况下使 align-items: flex-start;
得到正确应用。
堆栈片段
body {margin: 0; padding: 0;}
.box {
color: white;
width: 300px;
height: 300px;
background: red;
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
}
hr {
position: relative;
background: white;
height: 3px;
width: 75px;
align-self: flex-start;
margin: 0; /* added */
}
<div class="box">
<h1>Hello</h1>
<hr>
<p>Thanks</p>
</div>
关于html - 对齐 flex 容器内的 <hr> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405602/