CSS - Completely Filling Container With An Image
You may have noticed that I added images for each post as it appears in the home/overview page. You may have also noticed that the shape that the images needs to fit within is not a fixed size. It will dynamically adjust in width based on the size of the window the user is viewing the website within. This way the website will fit nicely on any screen size, whether it be a laptop, tablet, or phone. To see this for yourself, try shrinking/expanding the width of your browser window when on that page.
A single post may look like this...
or like this...
This dynamic size presents a problem for the image that should go within.
I decided that the best course of action would be to use a technique that would "crop" the image from the center (after having shrunk or expanded it) so that you could see as much of the image as possible, but it would completely fill the box it was within.
This is done using the CSS property/value pair of: background-size: cover;
.
If you want to perform a similar action, here is an example of the full CSS that could be used on a div to achieve the same thing.
width: 100%;
height: 10rem;
background-size: cover;
background-image: url(//files.programster.org/tutorials/builds/hp-microserver-nas/01.jpg);
background-position: center center;
background-position
, you may wish to use something like center top
as the value instead.
First published: 23rd September 2018