首页 > 解决方案 > 垂直响应 CSS 图像

问题描述

我知道我们可以像这样轻松地创建响应式水平图像。

.img-horiz-resp {
  max-width:100%;
  height:auto;
}

但是,就我而言,我需要:

然后,在垂直调整浏览器大小时,我希望“内容”适应它的大小。

我在这里尝试过:https ://codepen.io/cdemez/pen/qBbKVYp

但没有成功。

标签: cssresponsiveresponsive-images

解决方案


通过使用 VH 作为高度,您可以获得图像响应(也有其他方法,但这很简单)。VH 用于表示应该使用多少可用高度,例如百分比 (%)。100VH是从上到下的整个屏幕,不管你的屏幕大小。现在我将图像放在 css 文件中(并且仅将其用作背景,而不是背景图像),但如果您想在 html 文件中使用它,请记住将您的 with 设置为 100%。 https://jsfiddle.net/battleaxe/u07cfbog/#&togetherjs=lbxrukCzHi

HTML:

 * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    body {
      height: 100%;
      min-height: 100%;
      font-family: Arial, Helvetica, sans-serif;

      display: flex;
      flex-direction: column;
      align-items: center;
    }
    header {
      height: 6vh;
      width: 100%;
      background-color: #2e4b49;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    ul {
      width: 60%;
      display: flex;
      justify-content: space-between;
      list-style: none;
      color: #fff;
      text-transform: uppercase;
    }
    .content {
      height: 84vh;
      width: 100%;
      background: url("https://cdn.socloze.com/cdn/e_663aa122-718e-a8d3-301d-39f64b8523b0/ebdc5bef01506acc759b39f64b9cc917.jpg")
        no-repeat center center;
      background-size: contain;
      /* You can use background-size: cover; if you want the image to cover your whole free space. */
    }
    footer {
      height: 10vh;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #2e4b49;
      color: #fff;
    }
   




    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>Document</title>
      </head>
      <body>
        <header>
          <ul>
            <li>This</li>
            <li>Is</li>
            <li>a</li>
            <li>Header</li>
          </ul>
        </header>
        <div class="content"></div>
        <footer>
          <p>This is a footer</p>
        </footer>
      </body>
    </html>

您可以查找的内容是 VH 和 VW,它们的工作方式和使用方式。此外,尝试不同的背景尺寸(封面、包含等)。

祝你好运!


推荐阅读