【问题标题】:Vertical align of image图像垂直对齐
【发布时间】:2022-12-23 02:44:46
【问题描述】:

我正在尝试垂直对齐标题上的图像。那是我的实际代码,我将它水平对齐到中心。

header {
  background-color: blue;
  height: 118px;
  width: 1024px;
  text-align: center;
}

.container {
  margin-left: auto;
  margin-right: auto;
  width: 1024px;
}
<div class="container">
  <header>
    <img src="https://i.imgur.com/dKLmNz6.png" alt="JPAD Logo">
  </header>
</div>

我尝试搜索一个解决方案,可以让它在中心垂直对齐,但不能再通过文本对齐使其水平对齐:

header {
  background-color: blue;
  height: 118px;
  width: 1024px;
  text-align: center;
  display: flex;
  align-items: center;
}

.container {
  margin-left: auto;
  margin-right: auto;
  width: 1024px;
}
<div class="container">
  <header>
    <img src="https://i.imgur.com/dKLmNz6.png" alt="JPAD Logo">
  </header>
</div>

我只是真正开始 HTML+CSS。有什么建议么?

【问题讨论】:

  • 你想让图像水平和垂直居中吗?

标签: html css alignment


【解决方案1】:

使用 Flexbox,您可以向您的 flex 元素添加属性 justify-content:center

在这篇css-tricks 文章中,您可以找到有关如何使元素居中的好示例。

header {
  background-color: blue;
  height: 118px;
  width: 1024px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  margin-left: auto;
  margin-right: auto;
  width: 1024px;
}
<div class="container">

  <header>
    <img src="https://i.imgur.com/dKLmNz6.png" alt="JPAD Logo">
  </header>


</div>

【讨论】:

  • 那个 worksssssss 谢谢
【解决方案2】:

只需将 'justify-content: center' 添加到您的 flex 容器中。

header {

    background-color: blue;
    height: 118px;
    width: 1024px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container{

    margin-left:auto;
    margin-right:auto;
    width: 1024px;

}
img { display:block }
<div class="container">

        <header>
            <img src="https://i.imgur.com/dKLmNz6.png" alt="JPAD Logo">
        </header>


    </div>

【讨论】: