Kaboom Kaboom - 15 days ago 5
CSS Question

Overlay color on image with css and center text

I am trying to make it so when users hover over an item that is no longer in stock it will show them a message overlay on the image saying no longer in stock. This is working currently but I cannot seem the get the text to float in the absolute center of the block. It floats on the top in the center of the image.

Here's the HTML

<div class="store_no_stock_sizer">
<img src="/com/img/products/1.png" alt="Image">
</div>
<div class="store_page_product_title">Test Item</div>
<p>Out of Stock</p>


and the CSS I am using to overlay the image

.store_no_stock_sizer {
display: inline-block;
position: relative;
}
.store_no_stock_sizer:after {
opacity: 0;
}
.store_no_stock_sizer:hover:after {
max-width: 100%;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
outline: none;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: 99%;
display: block;
position: absolute;
background: #000;
color: #FFF;
opacity: 0.7;
content: "OUT OF STOCK";
}


Now this DOES WORK but it has the text in the top of the image when they hover over it rather then in the center of the image. I would use padding and such but since its a responsive page and image, I don't want a strict padding set to it.

Answer

You can use display: flex for dynamically centering text,

Also using align-items: center; and justify-content: center;

Like this:

.store_no_stock_sizer:hover:after {
        max-width: 100%;
        -webkit-border-radius: 3px;
        -moz-border-radius: 3px;
        border-radius: 3px;
        outline: none;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        height: 99%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        background: #000;
        color: #FFF;
        opacity: 0.7;
        content: "OUT OF STOCK";
}