html - 如何在不损失质量的情况下将背景图像居中?

标签 html css

幻灯片 div 是轮播的一部分,其中包含大小或纵横比不同的图像。如何在不损失质量的情况下将背景图像居中(无论大小如何)?我编写的代码非常适合普通尺寸的图像,但如果图像较小(30 像素 x 30 像素),它将被拉伸(stretch)以匹配 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;
}

最佳答案

你可以使用一个容器(.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>

关于html - 如何在不损失质量的情况下将背景图像居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54496234/

相关文章:

html - 文本在 <p> 标记中延伸出 <div> 一次吗?

html - 如何仅在内容可编辑的 div 达到其最大高度时显示滚动条?

javascript - 如何检测一个 <div> 是否接触到另一个 <div>?

html - 元素css、html如何分离

html - 如果不移动 "box",似乎无法将文本移到右边

html - 是否可以使用固定宽度的 verbatimTextOutput 并在 Shiny 中更改文本行?

jquery - 如何让一个元素响应另一个元素的点击? - CSS/jQuery

html - 不更改子 div 的背景过滤器

html - 如何等待 HTML 中的视频背景直到它完成然后查看正文部分的内容?

css - 是否有 CSS 父级选择器?