CSS background-image and background-size properties
To add style to your web elements, consider utilizing the CSS background-image property. For optimal formatting, try incorporating the background-size: cover;
rule. This directive adjusts the image based on the width of the container.
CSS:
.cont {
width: 200px;
height: 200px;
background-image: url('urlToImage100x300.jpg');
background-size: cover;
}
HTML:
<div class="cont"></div>
If you wish to vertically center your image, utilize background-position-y: center;
.
.cont {
width: 200px;
height: 200px;
background-image: url('urlToImage100x300.jpg');
background-size: cover;
background-position-y: center;
}
Incorporating HTML img tag
If using an <img />
tag is necessary, place the image within a container, specify the desired width
and height
, set overflow-y
to hidden, and adjust the image width to 100% for complete coverage.
CSS:
.cont {
width: 200px;
height: 200px;
overflow-y: hidden;
}
.cont img {
width: 100%;
}
HTML:
<div class="cont"><img src="image100x300.jpg" /></div>
View working demo CSS without y-axis centering here: https://jsfiddle.net/e2vt3sw6/
Access the demonstration with CSS including y-axis centering: https://jsfiddle.net/e2vt3sw6/1/
Explore a functioning example using the HTML img tag: https://jsfiddle.net/e2vt3sw6/2/
Testing was conducted with a 150x300px image placed in a 200x200px container.