Trying to fit an image inside a Div box that changes dimensions according to screen size. Still new to this.
I need this image to always keep it’s proportion and be cropped by the Div box that may be vertical or horizontal. Preferably I want the Image to be centered on the Div box and with a 5px bleed.
Optionally, is it also possible to set a focus point on the image so that point is what is centered when Div box changes size?
Many thanks!
Here’s my current code, where to improve so that Image gets cropped by Div?
body {
background: white;
display: flex;
height: 100vh;
}
div {
width: calc(100% - 50px);
height: calc(100% - 50px);
background: #f0e8e6;
overflow: hidden;
margin: auto;
display: flex;
}
#container {
max-width: auto;
overflow: hidden;
}
img {
width: calc(100% - 5px);
/* wrong calc? */
object-fit: contain;
}
<body>
<div>
<img src="https://euclois.xyz/desert-statue.jpg">
</div>
<style type="text/css">
html,
body {
margin: 0;
height: 100%;
overflow: hidden
}
</style>
</body>
4
Answers
I think using
object-fit: cover
on the img tag will do instead ofcontain
. Is this what you wanted to do: https://codesandbox.io/s/object-fit-issue-0n63pyuse
object-fit: cover;
for the img class, you have used contain.See here all possible values for
object-fit
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fitadd
object-fit: cover
on the image and also, instead of -5 width on the image, try padding on the wrapping div,This will work best as a CSS background.
background-size: cover
will expand/shrink the image to cover the entire background without distorting the aspect ratio.5px
"bleed" is achieved with a combination ofpadding: 5px
,background-clip: content-box
, andbackground-origin: border-box
.background-position
orbackground-position-x
andbackground-position-y
.