【问题标题】:How can I center a background image without loosing its quality?如何在不损失质量的情况下将背景图像居中?
【发布时间】:2019-02-02 18:35:21
【问题描述】:

幻灯片 div 是轮播的一部分,其中包含大小或纵横比不同的图像。无论大小如何,如何在不损失质量的情况下将背景图像居中?我编写的代码非常适合普通大小的图像,但如果图像更小(30 像素 x 30 像素),它将被拉伸以匹配 div 的宽度或高度。

<div class="slide"></div>

.slide {
    width: 100%;
    height: 400px;
    background-image: url('./assets/img4.jpeg');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    border: 1px solid red;
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以使用容器 (.imagecont):

    .container {
      width: 10em;
      border: 1px solid black;
    }
    
    .imagecont {
      position: relative;
      width: 10em;
      height: 10em;
    }
    
    img {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      max-width: 10em;
      max-height: 10em;
      margin: auto;
    }
    <div class="container">
      <div class="imagecont">
        <img src="https://google.com/favicon.ico">
      </div>
      <div class="imagecont">
        <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
      </div>
    </div>

    可变宽度的版本(尝试用鼠标调整容器大小)

    .container {
      border: 1px solid black;
      width: 5em;
      resize: horizontal;
      -moz-resize: horizontal;
      overflow: hidden;
    }
    
    .imagecont {
      position: relative;
      height: 10em;
      max-width: 100%;
    }
    
    img {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      max-width: 100%;
      max-height: 100%;
      margin: auto;
    }
    <div class="container">
      <div class="imagecont">
        <img src="https://google.com/favicon.ico">
      </div>
      <div class="imagecont">
        <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
      </div>
    </div>

    【讨论】:

    • 谢谢你成功了!但是你知道为什么它不适用于 % 吗?
    • @MedveTheFab,你想在哪里使用 %?
    猜你喜欢
    • 1970-01-01
    • 2019-10-26
    • 2021-10-13
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多