假设我有一个宽度 100px 的div,我的图像宽度为 UNKNOWN 。
有没有办法按照以下要求将图像设置为div的背景:
答案 0 :(得分:1)
CSS background-image
无法为您提供此级别的灵活性,但您可以使用<img>
来近似它:
div {
/* We'll be positioning the <img> relative to the <div>. */
position: relative;
/* Don't let an oversized background image stretch out the <div>. */
overflow: hidden;
}
div>img {
/* Since the image is an <img> element and not a background-image,
we don't have to worry about it shrinking, but we do need to
explicitly make it no smaller than the containing <div>. */
min-width: 100%;
/* Don't get in the way of positioning other elements. */
position: absolute;
/* Move the left edge of the image to the center of the <div>, then
shift it back by half the width of the <img>. Result: centered
image. */
left: 50%;
transform: translateX(-50%);
/* It's supposed to be a background image, so put it behind other
content. */
z-index: -1;
}
/* The rest is just for the sake of this example. */
div {
color: red;
border: 1px solid red;
resize: both;
}
<div>
<img src="https://i.stack.imgur.com/xXLKG.png">
Try resizing this <div>!
</div>
答案 1 :(得分:0)
背景图片无法使用容器缩放尺寸。
答案 2 :(得分:0)
制作其父级的内容width : 100%
将在此处运作!
.fixSize{
width:500px;
}
.image{
width:100%
}
&#13;
<!-- Now if i have a large image width:2500px -->
<div class="fixSize">
<img class= "image" src="https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg" alt="Large Image">
</div>
<!-- Now if i have a small image width:256px -->
<div class="fixSize">
<img class= "image" src="https://digitalpadm.com/wp-content/uploads/2017/07/Logarithmic-Image-Gray-level-Transformation-digitalpadm.bmp" alt="">
</div>
&#13;
答案 3 :(得分:0)
这是JavaScript的简单修复 Html代码
<div id="dv">
<img id="img" src="yourImageSource"/>
</div>
CSS代码
#dv {
width: 100px;
height: auto;
min-height: 200px;
overflow: hidden;
border: 2px solid black;
box-sizing: border-box;
}
#img {
height: 200px;
}
JavaScript代码
window.onload = ()=>{
var a = document.getElementById("dv");
var b = document.getElementById("img")
var c = a.getBoundingClientRect().width;
var d = b.getBoundingClientRect().width;
if(c < d){
b.style.marginLeft = (c - d)/2 + "px";
b.style.width = "auto";
} else {
b.style.marginLeft = "0px";
b.style.width = "100%";
}
}