如何在在HTML / CSS flexbox布局中居中图像?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (204)

有个项目基本上是一张照片和其他信息。我不太清楚如何对齐标题,使它们一致在同一行。图像应该居中。我使用了Flexbox,但是我正在寻找CSS grid来解决我的问题。请问有没有可以用用Flexbox实现的呢?我不确定我是否需要添加一些对齐标签。

<div class="pet-list">
  <div class="pet-item" ng-class="{'selected' : data.votedPet == pet.sys_id}" ng-repeat="pet in data.pets">
    <img class="img-responsive pet-image center-block" src="{{pet.photo}}"/>
    <div class = "pet-info">
      <h3>
        {{pet.name}}
      </h3>
      <p>
        Owner: {{pet.submitted_by}}
      </p>
      <p>
        {{pet.comments}}
      </p>
      <div class="button-container">
        <button ng-if="data.votedPet != pet.sys_id" ng-disabled= "c.disabled()" ng-click="c.vote(pet)" class="btn btn-info" role="button">
          Vote for {{pet.name}}! </button>
      </div>
    </div>
  </div>
</div>


    .selected {
    border-style: solid;
  border-width: 5px;
  border-color: #142667;
}

.pet-list{
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: flex-start;
}

.pet-image{
  vertical-align: top;
}

.banner{
  display: flex;
  justify-content: center;
  align-items: center;
}

.button-container{
  display: flex;
  justify-content: center;
  margin: 3%;
}

.pet-info{
background-color: #142677;
  position: relative;
}

.pet-info h3, p{
  color: white;
}

.pet-item{
  font-size: 16px;
  margin: 10px 1%;
  max-width: 310px;
  overflow: hidden;
  display: flex;
  padding: 0.5em;
  justify-content: center;
  flex-direction: column;
  text-align: center;
}




@media all and (min-width: 40em) {
  .pet-item {
    width: 50%;
  }
}
@media all and (min-width: 60em) {
  .pet-item {
    width: 33.33%;
  }
}

如果信息足够大,则使信息始终位于底部,图片位于最顶部,否则将其置于中心位置。

提问于
用户回答回答于

将样式更改为以下样式:

.pet-list{
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;

}

.pet-image{
  vertical-align: middle;
}

或者,您可以通过以下方式对页面中间的所有内容进行调整:

.pet-list{
    display: flex;
    flex: 1;
    min-height: 100vh;
    align-items: center;
    justify-content: center;
}

扫码关注云+社区

领取腾讯云代金券