【问题标题】:How to align vertically an item [duplicate]如何垂直对齐项目[重复]
【发布时间】:2021-09-14 05:48:51
【问题描述】:

对于这个愚蠢的问题,我很抱歉,但是来自 WPF 世界,我很难在 HTML/CSS 中对齐内容。

我正在使用 Vue 构建一个小应用程序,以便在这方面对自己进行一些训练,但这比我苦苦挣扎的时间要多一个多小时。

我正在构建一个标题,它应该有一个左右部分。

目前我有以下内容:

<template>
  <div class="layout-topbar">
    <div class="layout-topbar-left">
      <a href="/" class="logo">App name</a>
    </div>
    <div class="layout-topbar-right"></div>
  </div>
</template>

<style lang="scss" scoped>
a.logo {
  text-decoration: none;
  color: inherit;
}
.layout-topbar {
  height: 4rem;
}
.layout-topbar-left {
  margin: auto 0;
  height: auto;
}
</style>

我不明白为什么第二个 div(带有layout-topbar-left 类的那个即使使用margin: auto 0; 也能保持在顶部?

(当前的结构可能没有多大意义,但我将在alayout-topbar-left 内添加其他元素)

【问题讨论】:

  • div 是一个块元素,因此它可以占据整个宽度。如果要对齐它们,请参阅 CSS flexgrid.layout-topbar { display: flex; align-items: center; justify-content: space-between; }
  • “即使使用 margin: auto 0; 也能保持在顶部” - 您是否期望这会使元素相对于父高度居中?这在那个方向上不起作用,使元素居中的自动边距仅在水平方向上起作用,而不是在垂直方向上。 (在正常情况下,在 flexbox/grid 中有些不同。)

标签: html css


【解决方案1】:

要垂直对齐项目,您可以使用:

display: flex;
flex-direction: column; //align items vertically
align-items: center; //centers your items vertically

【讨论】:

    【解决方案2】:

    您可以为此使用display: flexalign-items。例如:

    a.logo {
      text-decoration: none;
      color: inherit;
    }
    .layout-topbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
    
    }
      <div class="layout-topbar">
        <div class="layout-topbar-left">
          <a href="/" class="logo">App name</a>
        </div>
        <div class="layout-topbar-right">Right Content</div>
      </div>

    【讨论】: