8

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

#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%;
}

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

4

8 回答 8

13

这是一个肮脏的方式:

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 仍然拥有一些空间,这将阻止鼠标指向它下面的东西。您可以使用指针事件来解决这个问题,但是 IE 将被抛在后面,并且图像本身也不会是指针。

于 2013-08-06T10:07:38.443 回答
4

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

CSS:

width: 100%; text-align: center; margin-top:50%
于 2013-08-06T09:29:35.697 回答
4

下面是我的建议。它适用于任何<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/

于 2019-04-12T20:25:55.980 回答
3

使用表格显示:

CSS

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

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

于 2018-11-07T05:32:25.177 回答
2

试试这个

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

#logo01{
    position:absolute;
    top:50%;
    left:50%;   
    cursor:pointer;
    max-width:45%;
    max-height:45%;
    display:table;
} 
于 2013-08-06T09:41:53.230 回答
1

您可以利用display:tableanddisplay: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/

您可以看到图像垂直居中对齐。同样在响应式风格的情况下,只需更改heightandwidth的值#logo_container

于 2013-08-06T09:53:09.207 回答
1

这个解决方案可能工作得很好:

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

于 2021-02-16T05:44:31.903 回答
-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;
}
于 2020-07-29T02:36:35.567 回答