How to make an image fit the size of the div by the background-image: url(') using javascript or css.

Asked

Viewed 441 times

0

I have a div which has size 200x300 and one which has 50x100, the 2 div will receive the background-image: url('') which the user informs, but he can put an image with size 1280x720, so the image will be showing a small piece in the div, How could I resize it to fit the div? In case, in one place have the size of 200x300 and elsewhere have the size of 50x100 using only javascript or CSS?

2 answers

1


This would be the easiest way

.place {
	width: 300px;
	height: 200px;
	background-image: url('http://lounge.obviousmag.org/tanto_mar/assets_c/2015/07/Blue-Water-thumb-920x575-115076.jpg');
	background-position: center;
	background-size: cover;
}
<div class="place"></div>

Using npm, you have this package here: https://www.npmjs.com/package/easyimage

  • It worked perfectly! I have difficulties with CSS, things that are solved so simple and I do not discover. Thank you Marcelo and those who responded!

  • Nothing guy a pleasure

0

You can use the "cover" property of css, do the following, it is worth remembering that it is not very advisable to use a very large image for something small

<div class="image" ></div>

.image{
background-image: url("seila.png");
background-size:cover;
}

Follow example in codepen https://codepen.io/anon/pen/bLLMVN

Browser other questions tagged

You are not signed in. Login or sign up in order to post.