shibbir ahmed
shibbir ahmed

Reputation: 1024

How can I center text on an image using Bootstrap?

On my website there is a "What we offer" section. I placed three images with text in this section. I want the text and the green background to be centered on the images on all devices. I used the following code, but it's not working.

Bootstrap HTML code:

<div class="row text-center">
    <h1>What we offer</h1>
    <hr class="separator">
    <div class="col-sm-4">
        <div class="we-offer">
            <img src="images/multiple-food_01.png" alt="" class="img-responsive center-block">
            <h3>Cooking Classes</h3>
        </div>
    </div>    
</div>

My custom CSS code:

.we-offer h3 { 
   position: absolute; 
   top:30%;
   text-align: center;   
   left: 0;
   right: 0;   
   border-top: 1px solid #fff; 
   border-bottom: 1px solid #fff; 
   border-right: 1px solid #fff; 
   padding: 10px;   
   color:#fff;
   background-color: rgb(162, 173, 0);    
   background-color: rgba(162, 173, 0, 0.5);    
   filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
   -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}

What it looks like now: enter image description here Can you show me how can I center the Cooking Classes text with green background box on the image to all device ?

More or less what I want:

enter image description here

Upvotes: 1

Views: 143

Answers (1)

Rob Scott
Rob Scott

Reputation: 8049

See Fiddle

The top: 50%; left: 50%; transform: translate(-50%, -50%); is what's going to give you ultimate centering.

You have a default margin-top: 20px on there that needs to be zero'd out. Also remove the left:0; and change all CSS to below:

.we-offer h3 { 
   position: absolute; 
   top:50%;
   left: 50%;
   transform: translate(-50%, -50%);
   white-space:nowrap;
   text-align: center;   
   margin: 0;
   border-top: 1px solid #fff; 
   border-bottom: 1px solid #fff; 
   border-right: 1px solid #fff; 
   padding: 10px;   
   color:#fff;
   background-color: rgb(162, 173, 0);    
   background-color: rgba(162, 173, 0, 0.5);    
   filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
   -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}

Please note you need CSS3 capability to do this.

Upvotes: 3

Related Questions