如何在多个设备上居中div

时间:2023-01-22 18:59:16

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?

我有一个div,其中包含一些包含图像的锚标签。无论设备的宽度是多少,有没有办法让div在多个设备中居中?

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.

每个锚标签具有固定的宽度和高度,并且取决于屏幕的宽度,有时2个锚标签连续显示,有时3个。

Here is my css:

这是我的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;
  }

2 个解决方案

#1


1  

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

如果位置静态(默认)你必须使用margin:0 auto;否则使用左:50%; margin-left :-( div的宽度的一半)

#2


0  

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.

试试这个img {margin-left:auto; margin-right:auto;}无论宽度如何,这都会将图像准确地置于容器中间。

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

如果您遇到高度问题,您也可以尝试:

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

#1


1  

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

如果位置静态(默认)你必须使用margin:0 auto;否则使用左:50%; margin-left :-( div的宽度的一半)

#2


0  

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.

试试这个img {margin-left:auto; margin-right:auto;}无论宽度如何,这都会将图像准确地置于容器中间。

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

如果您遇到高度问题,您也可以尝试:

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