调整图像以自适应 CSS 中的 div

huangapple go评论82阅读模式
英文:

Resizing image to autofit div in css

问题

我是非常新手的编程,正在寻求在CSS中将图像自适应到div中。我编写的代码只是在CSS中添加了div的背景图像,所以没有在主HTML代码中引用图像文件。

是否有一种方法可以在div的CSS中调整图像的大小,还是需要将其分为div的CSS和图像的CSS(我希望我说得有道理!)。

或者如果有一种完全不同的更有效的方法,请告诉我 - 任何帮助将不胜感激!

.test {
	border: 2px dashed #0087F7;
	background-color: #DCDCDC;
	background-image: url('download.png');
	background-repeat: no-repeat;
	background-position: center;
}
英文:

I am incredibly new to coding and am looking to autofit an image within a div in CSS. The code I've written just adds the background image in the CSS for the div, so haven't referenced the image file in the main HTML code.

Is there a way to resize the image within the div CSS or do I need to separate it out into div CSS and then image CSS (I hope I'm making sense!).

Or if there is a completely different way of doing it more efficiently please let me know - Any help would be greatly appreciated!

.test {
	border: 2px dashed #0087F7;
	background-color: #DCDCDC;
	background-image: url('download.png');
	background-repeat: no-repeat;
	background-position: center;
}

答案1

得分: 0

你可以使用 background-size 中的 containcover 属性来调整背景的大小。你还可以设置一个百分比。

div {
  width: 150px;
  height: 50px;
  display: inline-block;
  border: 1px solid;
  background: url("https://picsum.photos/150/150");
  background-repeat: no-repeat;
  background-position: center;
}

.cover {
  background-size: cover;
}

.contain {
  background-size: contain;
}
<div class="cover"></div>
<div class="contain"></div>
英文:

You can use the properties contain and cover in background-size to manipulate the background's size. You can also set a percentage.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

div {
  width: 150px;
  height: 50px;
  display: inline-block;
  border: 1px solid;
  background: url(&quot;https://picsum.photos/150/150&quot;);
  background-repeat: no-repeat;
  background-position: center;
}

.cover {
  background-size: cover;
}

.contain {
  background-size: contain;
}

<!-- language: lang-html -->

&lt;div class=&quot;cover&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;contain&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月3日 17:51:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定