I have a card with image, text and overlay gradient.
The image is much bigger than its parent div. The image is made responsive to the size of parent div. I need to position the image inside div a certain way, so I use object-position
for it.
However, when I try to position it, I get white space between the image and parent container, even though the image is bigger than the div.. I used position values from Figma which are :
position: absolute;
width: 386px;
height: 458px;
left: -33px;
top: -94px;
On the screenshot you can see how it should look like (on the left) and how it's done with the code below (on the right):
DEMO
https://github.com/meri-maki/stackoverflow-demo-ingrad
https://meri-maki.github.io/stackoverflow-demo-ingrad
.card {
border-radius: 24px;
width: 100%;
height: auto;
min-height: 328px;
max-height: 534px;
position: relative;
display: inline-block;
overflow: hidden;
}
.card img {
display: block;
vertical-align: bottom;
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
/* ----------IMAGE POSITIONING---------- */
object-position: top -94px left -33px;
}
/* ----------gradient---------- */
.card:after {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 0;
min-width: 100%;
height: 66%;
background: linear-gradient(0deg, #181818 0%, rgba(25, 23, 29, 0.447294) 48.44%, rgba(24, 24, 24, 0) 100%);
opacity: 0.9;
}
/* ----------caption---------- */
.caption {
z-index: 10;
position: absolute;
left: 4.27%;
right: 8.54%;
top: 63.41%;
bottom: 7.32%;
}
<div >
<img src="https://picsum.photos/1200" alt="">
<div >
<h4>Caption</h4>
</div>
</div>
I tried using transform: translate
but got same result. What could be wrong?
CodePudding user response:
You're shifting the image with negative position values. I'm not sure why, but you'd need to compensate by adding the reciprocal value to increase the size of the image accordingly.
Alternatively, set position to zero or center and eliminate those negative values.
.card {
border-radius: 24px;
width: 100%;
height: auto;
min-height: 328px;
max-height: 534px;
position: relative;
display: inline-block;
overflow: hidden;
}
.card img {
display: block;
vertical-align: bottom;
position: absolute;
object-fit: cover;
object-position: top -94px left -33px;
width: calc(100% 33px); /* <------------- HERE */
height: calc(100% 94px); /* <-------- AND HERE */
}
.card:after {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 0;
min-width: 100%;
height: 66%;
background: linear-gradient(0deg, #181818 0%, rgba(25, 23, 29, 0.447294) 48.44%, rgba(24, 24, 24, 0) 100%);
opacity: 0.9;
}
.caption {
z-index: 10;
position: absolute;
left: 4.27%;
right: 8.54%;
top: 63.41%;
bottom: 7.32%;
color: #fff;
}
<div >
<img src="https://picsum.photos/1200" alt="">
<div >
<h4>Caption</h4>
</div>
</div>