CSS Images
Image styling treats a picture as an element with a box of its own. The object-fit property controls how the picture fills that box.
A framed picture
A border and rounded corners style the picture like any other box. The radius value rounds each corner of the picture.
.pic {
border: 2px solid black;
border-radius: 8px;
}Fill the box
The box is wider and shorter than the source picture. Cover fills the whole box, and the top and bottom of the picture are cropped.
.pic {
width: 200px;
height: 100px;
object-fit: cover;
}Centre the picture
An image sits inline by default, like a word in a line. Centred text alignment on the body centres the image on the page.
body {
text-align: center;
}Example
body {
text-align: center;
}
.pic {
border: 2px solid black;
border-radius: 8px;
width: 200px;
height: 100px;
object-fit: cover;
}Key points
- object-fit: the property that sets how a picture fills its box
- Use cover to fill the box, and the edges of the picture are cropped.
- Use contain to fit the whole picture inside the box, with empty space left over.
- Aspect ratio: the ratio between the width and the height of a picture
- Leaving height as auto keeps the aspect ratio when only the width changes.
- A max-width of 100% keeps an image inside its container.
In this example, the body rule centres the inline image on the page. The picture rule gives the image a black border. The radius value rounds its corners. The width and height set a wider box, and cover fills that box with the picture.
Note
The display lesson shows a second way to centre an image, by making it a block.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does object-fit: cover do?