html - 将元素垂直对齐,上方 1/3 空间,下方 2/3 空间

标签 html css flexbox alignment

我有一个填充视口(viewport)高度和宽度的“英雄图像”。在这个 div 内有一个标题。我希望标题垂直对齐,以便任何可用空间位于上方三分之一和下方三分之二。

例如: 英雄图片 = 1000 像素高。 H1 = 400 像素高。所以上面的空间= 200px 下面的空间 = 400px

这是一个响应式布局,因此我不知道英雄图像或标题的高度。

使用 Flexbox 垂直居中很容易,但我需要下面更多的空间。 谁能建议我正确的方向?

这是到目前为止我的代码。请注意,我以前没有使用过 Flex,所以我真的不知道我在做什么。

.hero_image {
    min-height:100vh;
    background-color:yellow;
    display: flex;
    align-items: center;
    justify-content: center;
    }

.hero_image h1 {
    font-size:72px;
    padding-top:20px;
    }

<div class="hero_image">
    <h1>Heading <br>more text <br>last bit of text</h1>
</div>  

这是 JSFiddle 示例的链接 https://jsfiddle.net/yvf6tgh8/2/

最佳答案

为了处理布局部分,我将使用 CSS 网格:

CSS Grid Layout excels at dividing a page into major regions or defining the relationship in terms of size, position, and layer, between parts of a control built from HTML primitives.

Like tables, grid layout enables an author to align elements into columns and rows. However, many more layouts are either possible or easier with CSS grid than they were with tables. For example, a grid container's child elements could position themselves so they actually overlap and layer, similar to CSS positioned elements.

MDN

Try it online!

.hero_image {
  min-height: 100vh;
  background-color: yellow;
  display: grid;
  grid-template-rows: 1fr auto 2fr; /* here is the fun */
}

.hero_image>.content {
  width: 100%;
  display: flex;
  justify-content: center;
}

.hero_image h1 {
  font-size: 72px;
  padding-top: 20px;
}

/* just to show margin */
.hero_image>div:first-child,
.hero_image>div:last-child {
  background: red;
}

body {
  margin: 0;
}
<div class="hero_image">
  <div></div>
  <div class="content">


    <h1>Heading <br>more text <br>last bit of text</h1>
  </div>
  <div></div>
</div>

关于html - 将元素垂直对齐,上方 1/3 空间,下方 2/3 空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54477407/

相关文章:

html - 为什么属性对齐内容 :flex-end; have effect on displaying items when there are not multiple lines of items?

html - 如何在 css 的 flexbox 中保持 img 的纵横比?

javascript - 如何使用 HTML 5 Canvas 沿着弧形路径绘制文本?

java - java中的html截断器

jquery - 小于选择器

html - Flexbox 粘性页脚问题?

html - 表单字段溢出 Bootstrap 表单

javascript - 单击函数调用 javascript 然后重定向到 php 页面

javascript - 在 css 中将一个图像重叠在另一个图像上

html - react-native flexbox 中的全宽图像不拉伸(stretch)