【问题标题】:Need help vertically centering elements需要帮助垂直居中元素
【发布时间】:2017-04-30 01:01:26
【问题描述】:

我知道这里有很多关于如何垂直居中 div 的问题和答案,但我尝试了太多,但都没有奏效,有些似乎很复杂,所以我只需要有经验的人帮助知道最简单有效的解决方案。

下面是我的情况图片:

红色外部 div、内部左绿色 div 和内部右蓝色 div 都具有引导程序 pull-left 类。

那么我如何干净地确保我的内部蓝色 div(在绿色 div 内)也是一个图像,以及“一些文本”和作为按钮的黄色 div 都垂直居中,就像在图片。

这是 html(已编辑):

<div class="pull-left user-info">
    <div class="pull-left profile-image-wrap">
        <img class="profile-image" src="~/Content/Images/user.png" />
    </div>
    <div class="pull-left user-desc">
        <h1>Bok <strong>@Model.Korisnik.Ime</strong>!</h1>
        <button type="button" class="btn btn-default">Nova uplata</button>
    </div>
</div>

CSS:

.user-info {
    display: flex;
    border: 1px solid black;
    margin-top: 25px;
}

.profile-image-wrap {
    display: flex;
}

.profile-image {
  height: 70px;
  margin-right: 10px;

  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

}

.user-desc {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

结果如下:

【问题讨论】:

  • 你在使用 bootstrap 3 吗?
  • @MichaelCoker bootstrap v3.3.7

标签: css twitter-bootstrap flexbox


【解决方案1】:

您可以在父级和垂直居中的内容上使用flex,将flexflex-direction: column; align-items: center; justify-content: center; 一起使用

.user-info {
    display: flex;
    border: 1px solid black;
    margin-top: 25px;
}

.profile-image-wrap {
    display: flex;
}

.profile-image {
  height: 70px;
  margin: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.user-desc, .profile-image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="user-info">
  <div class="profile-image-container">
    <img class="pull-left profile-image" src="http://kenwheeler.github.io/slick/img/lazyfonz2.png">
  </div>
  <div class="user-desc">
    <h1>Bok <strong>@Model.Korisnik.Ime</strong>!</h1>
    <button type="button" class="btn btn-default">Nova uplata</button>
  </div>
</div>

【讨论】:

  • 不错!非常感谢,如果我将 .user-desc css 复制到 .profile-image ,知道为什么它不适用于图像吗?
  • 哦,等等,我可能需要将图像包装到一个 div 中
  • @m_bale 是的,这取决于您的其他 CSS 是什么。但我建议将图像包装在 div 中 - 将 img 作为 flex 子对象可能会与其他 CSS 产生奇怪的问题。
  • 刚刚尝试过,但不起作用:/,我唯一的图像css是margin-right和height
  • @m_bale 除非我的演示也坏了,否则请发布您的所有代码,否则我只能猜测。如果我的演示不适合你,请告诉我什么不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多