【问题标题】:Align an <hr> element inside a flex Container对齐 flex 容器内的 <hr> 元素
【发布时间】:2018-01-23 23:55:06
【问题描述】:

有谁知道如何在弹性容器中对齐&lt;hr&gt; 元素。当我做flex-start 时,所有其他元素都对齐,除了&lt;hr&gt;。我需要一个不在&lt;hr&gt; 元素上使用position: absolute 的解决方案,因为这会影响文档流并导致其他问题。

codepen: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>

【问题讨论】:

  • 有什么我可以添加或调整的,以使我的答案被接受吗?

标签: html css flexbox


【解决方案1】:

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;

堆栈sn-p

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>

【讨论】:

    【解决方案2】:

    将您的 hr 更改为

    background: white;
    height: 3px;
    width: 75px;
    margin-left: 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-25
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多