html - 对齐 flex 容器内的 <hr> 元素

标签 html css flexbox

有谁知道如何对齐 <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/

相关文章:

CSS,<div> 标签的高度和滚动

html - 具有 Bootstrap 动态高度的网格?

html - flex-start 和 baseline 有什么区别?

javascript - 不勾选时需要设置radio group的默认值

html - 如何以全高显示元素?

javascript - 在 HTML 的不同部分使用相同的 ng-controller 和不同的别名

html - 故意使两个柔性容器在相同的特定位置重叠

javascript - Element.prop ('scrollHeight' ) 为 Angular.js 中的不同列表项返回相同的值

html - 固定位置填充 div

css - 如何防止 GWT 覆盖 CSS