如何调整图像的高度以使用浏览器 window 进行裁剪?

How can I resize the height of an image to crop with the browser window?

我有一张图片,我想在加载网站时覆盖整个 window 浏览器。我已经知道了,随着浏览器 window 的宽度增加或减少,图像会调整大小,同时通过裁剪两侧来保持中心对齐和纵横比。但是,我想要这样,随着浏览器 window 的高度增加或减少,图像从底部 被裁剪 以便图像的底部始终对齐与浏览器的底部 window 和图像的顶部永远不会被切断。换句话说,当我向下滚动时,浏览器下方不应再有图像 window 可以滚动。我有以下 HTML 和 CSS 代码:

HTML:

 <div class="hs-slide hs-slide-count<?php echo $i; ?>">
      <div class="hs-slide-overlay"></div>
      <img src="<?php echo esc_url($hashone_slider_image); ?>" class="banner">
      <div class="hs-slide-caption">
        <div class="hs-slide-cap-title animated fadeInLeft">
          <?php echo esc_html($hashone_slider_title); ?>
        </div>

        <div class="hs-slide-cap-desc animated fadeInRight">
          <?php echo esc_html($hashone_slider_subtitle); ?>
        </div>
      </div>
    </div>

CSS:

img.banner{
  /* Set rules to fill background */
  min-height: 100%;
  min-width: 1024px;
  /* Set up proportionate scaling */
  width: 100%;
  height: auto;
  /* Set up positioning */
  position: relative;
  top: 0;
  left: 0;
  z-index: -1;
}
@media screen and (max-width: 1024px) { /* Specific to this particular image */
  img.banner {
left: 50%;
margin-left: -512px;   /* 50% */
  }
}

我该怎么做,最好没有 JavaScript?另外,我从一个关于用图像填充浏览器 window 的指南中得到了 CSS,我不知道为什么 HTML 中的最小宽度被专门设置为 1024px。

更新:

示例https://jsfiddle.net/jbx8nco4/4/

特定于您的代码的说明:您需要删除 .hs-slide 容器内的 <img> 并改为使用背景图像。将背景图像添加到 .hs-slide 后(参见下面的代码),.hs-slide 元素需要一个高度才能显示。您可以显式设置一个或让元素适应其内容的高度。对于后者,您需要从 .hs-slide-caption 中删除所有定位,并给它一个 padding-top 和 padding-bottom。为简单起见,我在示例中设置了一个明确的高度:

.hs-slide {
  height: 800px;
  background-image: url(http://placekitten.com/1000/500); /* replace with your image */
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center top;
}

此代码的 shorthand 符号为:

background: url(//placekitten.com/1000/500) center top / cover no-repeat;

我在评论的第一个版本中提到的 background-attachment: fixed 不需要,因为您希望图像随页面滚动。

顺便说一句:由于您现在有两张背景图像,其中一张是 .hs-slide-overlay 的一部分,您可以尝试使用 [=27= 组合两张背景图像来摆脱叠加层].

旧答案:

我不是很确定,但听起来你想要的可以通过使用 CSS background-image 来实现。我想不出使用 HTML img 标签的 Javascript-free 解决方案。

您需要将背景图像添加到任何延伸到视口全宽和全高的元素,然后设置适当的属性,最重要的是 background-sizebackground-position

body {
  width: 100%;
  height: 100%;
  background-image: url(//placekitten.com/1000/500);
  background-repeat: no-repeat;
  background-size: cover; // cover the whole area with the image
  background-position: top; // expand image from the top
  background-attachment: fixed;
}

背景属性的 shorthand 版本为:

background-image: url(//placekitten.com/1000/500) no-repeat top fixed;
background-size: cover;

这是一个活生生的例子:https://jsfiddle.net/jbx8nco4/2/

请记住,旧版浏览器不支持 background-size: cover

有关使用背景图像覆盖整个页面的更多信息和更多技巧,请参阅:https://css-tricks.com/perfect-full-page-background-image/