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>
CodePudding user response:
I think using object-fit: cover
on the img tag will do instead of contain
. Is this what you wanted to do: https://codesandbox.io/s/object-fit-issue-0n63py
CodePudding user response:
use 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-fit
CodePudding user response:
add object-fit: cover
on the image and also, instead of -5 width on the image, try padding on the wrapping div,
div {
width: calc(100% - 50px);
height: calc(100% - 50px);
background: #f0e8e6;
overflow: hidden;
margin: auto;
display: flex;
padding: 5px;
}