使图像适合剩余的可用高度

问题描述 投票:0回答:1

我的任务是根据图像开发一个网站。我有这张照片:

这部分显然分为两部分:图片和下面的文字。但是,整个部分的高度必须为 100vh。正如您所看到的,文本元素之间有一定的间距。如何使图像适合可用的剩余高度?

这是代码

* {
  margin: 0;
  padding: 0;
}

html {
  font-family: "Open Sans", sans-serif;
  font-size: 16px;
  color: #333333;
}

.hero {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.hero img {
  /* width: 100%; */
}

.hero>div {
  flex-grow: 1;
  max-width: 1280px;
  padding: 0 24px;
}

.hero h1 {
  font-size: 32px;
  line-height: 1.25em;
  font-weight: 800;
  margin-bottom: 24px;
}

.hero p {
  max-width: 1024px;
  font-size: 16px;
  line-height: 1.5em;
  margin-bottom: 32px;
}

a[href="#facts"] {
  margin: 0 auto;
  display: inline-block;
  margin-bottom: 16px;
}
<section id="hero" class="hero">
  <img src="assets/hero.jpg" alt="2018" width="1980" />
  <div>
    <div>
      <h1>People of the Year</h1>
      <p>
        Some people do more for humanity. Us, the People of the Year foundation, have hand-picked the ones we think have done one small step for themselves and a giant leap for us all and are providing them with the platform they deserve to be seen on.
      </p>

      <a href="#facts">
        <span>More</span>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                        </svg>
      </a>
    </div>
  </div>
</section>

遗憾的是,代码中的图像无法加载。不过,我想你已经明白了。如果您有任何疑问,请随时询问。

html css image-size
1个回答
0
投票

用另一个 div 包裹图像。另外,向包含文本的 div 添加一个类,并且不要再在 css 中使用 .hero > div 选择器,因为现在有两个具有不同用途的 div。

  <div class="hero-image-wrapper"> <!-- Wrap the image -->
    <img src="assets/hero.jpg" alt="2018" />
  </div>
  <div class="hero-text"> <!-- Add a class hero-text -->
    <div>
      <h1>People of the Year</h1>
      <p>
        Some people do more for humanity. Us, the People of the Year foundation, have hand-picked the ones we think have done one small step for themselves and a giant leap for us all and are providing them with the platform they deserve to be seen on.
      </p>

      <a href="#facts">
        <span>More</span>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                        </svg>
      </a>
    </div>
  </div>

现在,为图像包装器指定一个 relative 位置并将 flex 设置为 1。这样,div 将占用该部分的剩余空间。

对于图像,将位置设置为 absolute 并将 max-height 设置为 100%

另外,不要忘记将 .hero div 选择器更改为 .hero-text

.image-wrapper {
  flex:1;
  position:relative;
}

.image-wrapper img {
  position:absolute;
  max-height:100%;
}

// Your code, changed the selector
.hero-text {
  max-width: 1280px;
  padding: 0 24px;
}
© www.soinside.com 2019 - 2024. All rights reserved.