Center a div in a div with position absolute

Hey there.

I’d like to center a sale-tag in the product image. I’ve tried it with position absolute since the parent is relative but it behaves weirdly when resizing the viewport.

Site: click me

Password: siesoh

1 Like

Hi @itsolidude12 ,

Yes, you can use the position absolute on this.

  1. From your Admin Page, click Online Store > Themes >Actions > Edit code
  2. In the Asset folder, open the custom.css
  3. Paste the code below at the very bottom of the file.
.grid-product__tag.grid-product__tag--sale {
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    width: 100%;
    height: max-content;
}
1 Like

Works like a charm but I’ve just noticed that it is not the center of the product image, rather the center of the whole tile since that is the parent. Is there a workaround for this?

1 Like

Hi @itsolidude12 ,

Yes of course. Try the following code instead. Replace the code I provided with the code below

.grid-product__tag.grid-product__tag--sale {
    position: absolute;
    transform: translate(-50%, -50%);
    top: calc(50% - 30px);
    left: 50%;
    width: 100%;
    height: max-content;
}
1 Like

Would it make sense to use flexbox? Since it would be easier to align the children in there better as well?

1 Like

Hi @itsolidude12 ,

It would be unnecessary and not a best solution to use flex box in this case because of the element placements. The element sale is not a inside the image.

1 Like