CSS object-position — Code Challenge
Put choose an image crop focus into practice. Rebuild the example from its HTML, then compare your result with the CSS solution. Change the content and the viewport before calling it finished.
How it works
- Object-position moves replaced content within its box. It is useful for keeping a subject visible when cover crops an image.
- The preview uses a tiny embedded image so it does not need external downloads. Replace it with a real local asset when evaluating image quality and cropping.
- Keep meaningful alternative text in the HTML and reserve dimensions to avoid layout shifts during image loading.
Your task
Use the HTML below to explore this rule: Object-position moves replaced content within its box. It is useful for keeping a subject visible when cover crops an image. Write your own CSS before opening the solution. Then replace the heading with a longer one and verify that the content is still readable.
Review the CSS solution
.photo { width: 100%; height: 180px; object-fit: cover; object-position: 75% 25%; }
A solution to compare
The HTML supplies the content; the CSS below styles it. Open both together in the playground, then change the lesson rules at the end of the stylesheet.
<figure class="card"><img class="photo" width="120" height="80" alt="Orange circle on a blue background above a green strip" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAABQCAIAAABd+SbeAAABEklEQVR4nO3aSxHCQBRE0QhDABowgAD0sI4LLGEBC2R+mfScqrtP11lm3vZ8fzSg7fQFiwQadFagQWcFGnRWa0F/9/s/ge5O3I87H7qAuAd3MnQlcVvuWOiGyk2sM6GbK9dbB0J3Uq60ToPuqlxjHQU9QLnYGjToWZXLrEGDnli5wBo06LmVj1qDBg16tkCDBg0a9LyBBg0aNOh5Aw06C9rfO9Bx0F5YQMdBewUHHQftUinHunhVILRr0mtbV+6JhXbxfzHuVjPyoYu52w5YBfoQd49PrwV9YqBBZwUadFagR0HfXg8NCDTorECDzgo06KxAg84KNOisQIPOCjTorECDzgo06KxAg84KNOisQIPO6gd12QwrHUBvEQAAAABJRU5ErkJggg=="><figcaption>A small embedded image for experimenting with cropping and effects.</figcaption></figure>
body { margin: 0; padding: 24px; font-family: system-ui, sans-serif; color: #25332d; background: #f4f7f2; }
.card { padding: 20px; background: white; border: 1px solid #d4dfd6; }
h2 { margin-top: 0; }
p { line-height: 1.6; }
a { color: #17634c; }
.badge { display: inline-block; margin-bottom: 12px; font-size: .8rem; }
.layout { display: grid; gap: 16px; }
.photo { width: 100%; height: 160px; background: linear-gradient(135deg, #e4af6b, #668cba); }
button, input, select { font: inherit; padding: 8px; }
label { display: block; margin-block: 12px 4px; }
/* This lesson */
.photo { width: 100%; height: 180px; object-fit: cover; object-position: 75% 25%; }
Object-position moves replaced content within its box. It is useful for keeping a subject visible when cover crops an image.