英文:
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
中的 contain
和 cover
属性来调整背景的大小。你还可以设置一个百分比。
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("https://picsum.photos/150/150");
background-repeat: no-repeat;
background-position: center;
}
.cover {
background-size: cover;
}
.contain {
background-size: contain;
}
<!-- language: lang-html -->
<div class="cover"></div>
<div class="contain"></div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论