提问者:小点点

如何在CSS中有背景色,如果图像不是一定的大小?


我有这个代码:

null

<style>
body {
font-family: Arial, sans-serif;
font-size: 14px;
}
div.nyc {
width: 600px;
border: 1.5px;
}
.myimage {
width: 248px;
height: 186px;
}
.myimage {
background-color:#E7E82;
}
</style>

<H2>Used Cars for Cash in Queens, NY</H2>

<div class="nyc">
<img class="myimage" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/1989_Honda_Civic_GL_sedan_%2824990238761%29.jpg/1024px-1989_Honda_Civic_GL_sedan_%2824990238761%29.jpg">
<h3>Honda Civic 1.4 GL</h3>
<p>1989. Crystal green, this sedan is an import from Australia over 25 years old! $2,500</p>
<img class="myimage" src="https://i.imgur.com/lOhCCzD.jpg">
<h3>Burstner A Class</h3>
<p>More info... due soon! POA</p>
</div>

null

我怎么能用CSS使它的图像一定的宽度-即。 不是248px宽186px高的图像可以得到背景,但是在这个宽度下的图像可以得到颜色?

如果你能帮我的话我会很感激的。


共1个答案

匿名用户

如果我能理解你的问题,你可能会想要这样的东西,

null

<style>
  body {
    font-family: Arial, sans-serif;
    font-size: 14px;
  }
  
  div.nyc {
    width: 600px;
    border: 1.5px;
  }
  
  .myimage {
    width: 248px;
    height: 186px;
  }
  
  .myimage {
    background-color: red;
    object-fit: contain;
  }
</style>

<H2>Used Cars for Cash in Queens, NY</H2>

<div class="nyc">
  <img class="myimage" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/1989_Honda_Civic_GL_sedan_%2824990238761%29.jpg/1024px-1989_Honda_Civic_GL_sedan_%2824990238761%29.jpg">
  <h3>Honda Civic 1.4 GL</h3>
  <p>1989. Crystal green, this sedan is an import from Australia over 25 years old! $2,500</p>
  <img class="myimage" src="https://i.imgur.com/lOhCCzD.jpg">
  <h3>Burstner A Class</h3>
  <p>More info... due soon! POA</p>
</div>