使用flexbox垂直对齐div(Align divs vertically using flexbox)

编程入门 行业动态 更新时间:2024-10-25 08:26:32
使用flexbox垂直对齐div(Align divs vertically using flexbox)

我正在尝试使用flexbox垂直对齐三个div块。

我可以让它们水平对齐,但不能垂直对齐。

我究竟做错了什么?

.banner {
  padding-top: 10px;
  padding-bottom: 10px;
  background-color: #01b9d5;
  color: white;
  height: 55px;
}
.banner-align {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid green;
}
.banner-hero {
  flex: 1;
  align-self: center;
  max-width: 50%;
  border: 1px solid red;
  text-align: center;
  display: inline-block;
}
.banner-left {
  align-self: flex-start;
  flex: 1;
  border: 1px solid green;
  display: inline-block;
}
.banner-right {
  align-self: flex-end;
  flex: 1;
  text-align: right;
  border: 1px solid yellow;
  display: inline-block;
} 
  
<div class="banner">
  <div class="container banner-align">
    <div class="banner-left">
      Left Block
    </div>
    <div class="banner-hero">
      <b>Title</b>
    </div>
    <div class="banner-right">
      Right block
    </div>
  </div>
</div> 
  
 

这是一个小提琴: https : //jsfiddle.net/zqc1qfk1/1/

I'm trying to align three div blocks vertically using flexbox.

I can get them horizontally aligned correctly, however not vertically.

What am I doing wrong?

.banner {
  padding-top: 10px;
  padding-bottom: 10px;
  background-color: #01b9d5;
  color: white;
  height: 55px;
}
.banner-align {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid green;
}
.banner-hero {
  flex: 1;
  align-self: center;
  max-width: 50%;
  border: 1px solid red;
  text-align: center;
  display: inline-block;
}
.banner-left {
  align-self: flex-start;
  flex: 1;
  border: 1px solid green;
  display: inline-block;
}
.banner-right {
  align-self: flex-end;
  flex: 1;
  text-align: right;
  border: 1px solid yellow;
  display: inline-block;
} 
  
<div class="banner">
  <div class="container banner-align">
    <div class="banner-left">
      Left Block
    </div>
    <div class="banner-hero">
      <b>Title</b>
    </div>
    <div class="banner-right">
      Right block
    </div>
  </div>
</div> 
  
 

Here is a fiddle: https://jsfiddle.net/zqc1qfk1/1/

最满意答案

只需启用容器上的wrap并为每个弹性项目指定width: 100% :

.banner-align { display: flex; flex-wrap: wrap; } .banner-align > * { flex: 0 0 100%; }

现在每个flex项消耗行中的所有空间,强制其他元素创建新行。

修改小提琴

Simply enable wrap on the container and give each flex item a width: 100%:

.banner-align { display: flex; flex-wrap: wrap; } .banner-align > * { flex: 0 0 100%; }

Now each flex item consumes all the space in the row, forcing other elements to create new rows.

revised fiddle

更多推荐

本文发布于:2023-04-29 07:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:div   flexbox   Align   vertically   divs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!