如何保持图像居中和响应?

时间:2013-08-06 09:18:23

标签: css position responsive-design

我有一个图像,水平和垂直居中

#logo01{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-146px;  // half of height
    margin-left:-229px;  // half of width
    cursor:pointer;
}

现在我需要一个响应式设计,所以:

#logo01{
    max-width:45%;
    max-height:45%;
}

它有效,但位置丢失了。如何保持图像居中并同时响应?

8 个答案:

答案 0 :(得分:9)

这是一种肮脏的方式:

JSFiddle

<div class="shadow"><img class="logo" src="http://placehold.it/1000x1000" /></div>
div.shadow {
    position:absolute;
    max-width:45%;
    max-height:45%;
    top:50%;
    left:50%;
    overflow:visible;
}
img.logo {
    position:relative;
    max-width:100%;
    max-height:100%;
    margin-top:-50%;
    margin-left:-50%;
}

诀窍是使用div.shadow作为“维度持有者”,因此百分比可以正常工作。

我称它为脏,因为阴影div仍然拥有一些空间,这将阻止鼠标指向它下面的东西。您可以使用pointer event来解决这个问题,但是IE会被遗忘,图像本身也不会被指向。

答案 1 :(得分:3)

尝试使用以下css作为图像的容器。

CSS:

width: 100%; text-align: center; margin-top:50%

答案 2 :(得分:2)

试试这个

http://jsfiddle.net/hAH6u/2/

#logo01{
    position:absolute;
    top:50%;
    left:50%;   
    cursor:pointer;
    max-width:45%;
    max-height:45%;
    display:table;
} 

答案 3 :(得分:1)

您可以使用display:tabledisplay:table-cell属性来实现此目标。

<强> HTML:

<div id='logo_container'>
    <h1 id='logo'><img src = 'http://s18.postimg.org/rwpoh1vo9/forbidden.jpg' alt = 'Logo'/></h1>
</div>

<强> CSS

#logo_container {
    display:table;
    height:100px;
    width:100px;
    margin:0 auto;   
    text-align:center;
    border:1px solid #333;
}

#logo {
    display:table-cell;
    vertical-align:middle;

}
#logo img {
    max-height:80%;
    max-width:80%;
}

这是小提琴:http://jsfiddle.net/Qe2vG/

您可以看到图像垂直对齐。如果是响应式样式,只需更改height的{​​{1}}和width

答案 4 :(得分:0)

简单且高度有限:

CSS

img {
    max-width: 100%;
    height: auto;
    max-height: 300px;
    display: table;
    margin: 0 auto;
}

http://jsfiddle.net/herbowicz/a5kumqtv/

答案 5 :(得分:0)

以下是我的建议。它适用于任何<div> <img>和...

<div class="parent"> 

    <img class="responsive center" src="http://placekitten.com/800/600">

</div>

,css代码为:

.responsive{
   max-width:100%;
   max-height:100%;
 }

.center{
  position: absolute;
  top: 50%;
  left: 50%; 
  transform: translate(-50%, -50%);
}

.parent{
  position: relative;
}

只需在此处找到并测试现场演示: https://jsfiddle.net/veuodbk7/2/

答案 6 :(得分:0)

这个解决方案可能很好用:

img {
        max-height: 100%;
        max-width: 90%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
      }

答案 7 :(得分:-1)

由于大多数现代浏览器现在都支持CSS网格,因此我使用CSS网格。我知道这是一篇过时的文章,但是对于以后不了解CSS网格的任何人,您都应该研究一下它,它非常有帮助。

无论如何,这是我的解决方案:

在图像周围创建一个div并为其指定一个类名,以便您的HTML如下所示:

<div class="center-image">
  <img src=.... >
</div>

然后在您的CSS中添加以下内容:

.center-image {
  display: grid;
  justify-items: center;
}

您的图像应居中(水平)。如果您希望它也垂直居中,只需添加:

align-items: center;

您的div样式如下:

.center-image {
  display: grid;
  justify-items: center;
  align-items: center;
}
相关问题