1

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;
}
adamjamesb
  • 35
  • 6
  • 4
    Does this answer your question? [Stretch and scale a CSS image in the background - with CSS only](https://stackoverflow.com/questions/1150163/stretch-and-scale-a-css-image-in-the-background-with-css-only) – Markus Zeller Jan 03 '20 at 09:54
  • If you want to do it with a background image see the first duplicate, if you want to do it with an actual image tag, then I would use object fit - see second duplicate – Pete Jan 03 '20 at 10:00

1 Answers1

0

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

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>
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30