【问题标题】:CSS keep height, crop width in a divCSS在div中保持高度,裁剪宽度
【发布时间】:2018-08-23 17:30:13
【问题描述】:

我找了好久,还是没有找到准确的答案。 我有一个<div>,其宽度占屏幕的 100%,高度固定为 600 像素。 我想向 div 添加背景图片,其图片高度适合<div> 高度(600 像素且无图片裁剪)。每当我修改屏幕的宽度时,高度应始终保持 600 像素。然后图片将居中并在宽度方向上裁剪。

【问题讨论】:

    标签: html css


    【解决方案1】:

    试试这个:

    .container {
      width: 100%;
      height: 600px;
      background: url('https://images.pexels.com/photos/268415/pexels-photo-268415.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
      background-repeat: no-repeat;
      background-position: center;
      background-size: auto 100%;
    }
    <div class="container"></div>

    【讨论】:

      【解决方案2】:

      你试过了吗

      `
          background-image: url('your-image.gif');
          background-repeat: no-repeat;
          background-attachment: fixed;
          background-position: center; 
      
          `
      

      【讨论】:

      • 它几乎可以工作。唯一的问题是它还会裁剪图片的高度。例如,如果图片是 700px,它将从图片中裁剪 100px。 BTW 来定义 div 的高度,我使用的是 min-height: 600px;
      【解决方案3】:

      我想这就是你要找的:

      body {
        margin: 0px;
        padding: 0px;
      }
      
      div {
        width: 100vw;
        height: 600px;
        background: url('https://wallpaperbrowse.com/media/images/704532.jpg') no-repeat;
        background-size: 100% 600px;
        float: left;
        background-position: center;
      }
      <div>
        test
      </div>

      希望这对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-02
        • 2016-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-11
        • 2013-05-08
        • 1970-01-01
        相关资源
        最近更新 更多