css切断而不是按比例缩小

时间:2017-08-15 19:42:32

标签: html css

使用以下css,我尝试使用附加的图像作为背景图像。我期望图像以可扩展的方式调整大小,因为我使浏览器变小,然而,在600px时,女人的头部不再可见。换句话说,不是减少图像内容的比例(即按比例缩小),而是简单地切断图像的右侧。有没有办法缩小图像,而不是在减小浏览器大小时将css切断它的右侧?

html {
    height: 100%;
}
body {
    font-family: Lato, sans-serif;
    color: #333;
    font-size: 15px;
    line-height: 23px;
    font-weight: 300;
}
.hero-section {
    width: 100%;
    background-image: url('./3479295472_7d97d686e4_b_couple.jpg');
    background-position: 50% 45%;
    background-size: cover;
}

<div class="hero-section">
  <div class="hero-overlay-section">
    <div class="container hero-container w-container">
    <h1 class="hero-title" data-ix="hero-fade-in" style="opacity: 1; transform: translateX(0px) translateY(0px) translateZ(0px); transition: opacity 500ms, transform 500ms;">Jim</h1>
    <h1 class="and hero-title" data-ix="hero-fade-in-2" style="opacity: 1; transition: opacity 1500ms;">&amp;</h1>
<h1 class="hero-title" data-ix="hero-fade-in-3" style="opacity: 1; transform: translateX(0px) translateY(0px) translateZ(0px); transition: opacity 500ms, transform 500ms;">Karen</h1>
<div class="hero-divider-line" data-ix="hero-fade-in-4" style="opacity: 1; width: 120px; transition: opacity 500ms, width 500ms;"></div>
    <div class="hero-date-wrapper">
    <h2 class="hero-date-title" data-ix="hero-fade-in-5" style="opacity: 1; transition: opacity 500ms;">November 5th, 2018</h2>
    </div>
</div>
</div>
</div>

enter image description here

请注意,根据对this SO question background-size的评论应该有所帮助,但不在我的情况下。

更新

我也试过并得到了相同的结果(一旦我缩小了浏览器尺寸,女人的头就会被切断)。

background-size: contain;
background-repeat: no-repeat;

the (cut off) image with my browser at 600px wide

4 个答案:

答案 0 :(得分:2)

其他人对background-size: cover;background-position: center center的评价是正确的。

基本上,您有两种选择。

  1. 您可以强制图像永远不会被裁剪。最好的例子是<img>的默认行为。它会压扁并调整大小,但不会被裁掉。这样做的缺点是你必须保持图像的原始宽高比。

  2. 您可以忽略图像的宽高比,并告诉它填充容器,无论比例如何。这是background-size: cover; background-position: center center;解决方案。您可以使用该位置,以便不会裁剪重要部分。

  3. 如果您必须保持纵横比,让它填充容器,那么唯一的解决方案是顶部/底部或左/右的黑条(如在4:3电视上观看宽屏电影。)

答案 1 :(得分:1)

您无法显示图像以适合任何尺寸的容器,您必须丢失一些部件。

您可以做的是选择要显示的图像中最重要的部分,这可以通过操纵background-position

来完成

通常,在大多数情况下,最重要的部分是中心。 所以我们使用background-position: 50% 50%; background-size: cover;

你可以从这开始。

答案 2 :(得分:1)

有几种方法可以解决此问题,其中最好的方法是使用HTML5。 这是代码:

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

可以在git push gitlab --all

中找到代码的来源以及其他方法和演示

答案 3 :(得分:1)

为身体添加高度(以像素为单位)。我添加了700px,但您可以添加任何您喜欢的内容。

在英雄部分中,将CSS更改为以下内容:

    .hero-section {
    width: 100%;
    height: 100%;
    background-image: url('./3479295472_7d97d686e4_b_couple.jpg');                         
    background-size: contain;
    background-repeat: no-repeat;
   }

似乎关键是指定高度和宽度以及背景大小和背景重复指令。

可以根据您的喜好调整高度和宽度,图像也会缩放。