Teja Reddy
Teja Reddy

Reputation: 571

How to center a div on multiple devices

I have a div which contains some anchor tags which contains an image. Is there a way by which i can center the div in multiple devices no matter what the width of devices is?

Here is the code:

 <div class="jaffa">
       <a href="#">
         <img src="" >
         <span>sample text</span></a>
       <a href="#">
         <img src="" >
         <span>sample text</span></a>
       <a href="#">
         <img src="" >
         <span>sample text</span></a>
     </div>

Each anchor tag has a fixed width and height and depending on width of screen some times 2 anchor tags display in a row and sometimes 3.

Here is my css:

 @media(max-width:480){
  .jaffa a{
  width:200px;
  height:90px;
  padding:20px;
  }
  @media(min-width:481){
  .jaffa a{
  width:140px;
  height:90px;
  padding:20px;
  }

Upvotes: 0

Views: 161

Answers (2)

Molnia
Molnia

Reputation: 60

try this img {margin-left: auto; margin-right: auto;} This will center the image exactly in the middle of the container no matter the width is.

If you face any problems with the height you can also try:

margin-top:auto; margin-bottom: auto;

Upvotes: 0

Amin Jafari
Amin Jafari

Reputation: 7207

if position static (default) you have to use margin:0 auto; else use left:50%; margin-left:-(half of the width of your div)

Upvotes: 1

Related Questions