How to display hr horizontally with flex?

2020-03-23 18:42发布

When using flexbox for styling, if the parent container is set to display: flex it will cause the <hr /> to be displayed vertically instead of horizontally.

.container {
  display: flex;
  flex: 1;
}
<div class='container'>
  <h2>Test</h2>
  <hr />
</div>

标签: html css flexbox
2条回答
冷血范
2楼-- · 2020-03-23 18:51

Use flex-grow: 1 or width: 100% so it will grow to match the width of the parent. You probably want to use that in combination with flex-wrap: wrap on .container if you plan on putting more flex children in .container

.container {
  display: flex;
  flex: 1;
}

hr {
  flex-grow: 1;
  /* width: 100%; */ /* or this */
}
<div class='container'>
    <hr>
</div>

查看更多
手持菜刀,她持情操
3楼-- · 2020-03-23 19:06

The reason for this is that default value of align-items is stretch so hr will get the same height as largest element in flex-container or in this case h2. And default value for justify-content is flex-start so width of hr is 0.

Easy way to fix this is to use flex-wrap: wrap on parent element and flex: 0 0 100% on hr

.container {
  display: flex;
  flex-wrap: wrap;
}
hr {
  flex: 0 0 100%;
}
<div class='container'>
  <h2>Test</h2>
  <hr>
</div>

查看更多
登录 后发表回答