Positioning a div accurately on an image using object-fit

Feedback

Question:

I’m looking to overlay a div onto an image, specifically a cupcake that is represented by

.

As an illustration, my intention is to position the div above the crimson cherry, in this manner

.

As the dimensions of my image are flexible and I have applied

object-fit: cover;

to my CSS, the position of the div needs to adjust accordingly with any changes in the image’s size.

Applying

position: absolute;

to an image with fixed dimensions is sufficient, but when

object-fit: cover;

is present, the image may shift as the user resizes it. How can I ensure that my div remains in its precise position during such resizes?

Please let me know if my inquiry is unclear due to my non-native English proficiency. Thank you.


Solution 1:

To obtain precise top and center alignment of a div, consider utilizing the

CSS

and

calc() function

techniques.

#box{
  width:auto;
  height:auto;
  position:relative;
  overflow:hidden;
}
img{
  width:100%;
  min-height:100%;
  object-fit:cover;
}
#box > .bx{
  position:absolute;
  width:60px;
  height:60px;
  background:#111;
  top:5%;
  left:calc(100% - 60%);
  color:#fff;
}

Text


Solution 2:


Your question has been resolved. To position, try using percentage values.

.my_cover_div {
    position: absolute;
    left: 60%;
    top: 5%;
}

This article could prove helpful for achieving precise centering.

Frequently Asked Questions

Posted in Css