HTML视口中的中心图像(不含JavaScript)

Mik*_*ike 11 html css image viewport

我有一个我想在浏览器中显示的图像,以便:

  1. 如果图像小于浏览器视口,则图像以水平和垂直方向居中.
  2. 如果图像大于视口,则缩小图像以尽可能多地填充视口,而无需调整图像的纵横比.同样,图像在水平和垂直方向上居中.

不想使用JavaScript ; 什么是最好/最具语义的HTML和CSS来做到这一点?

更新我被要求澄清语义:图像是内容; HTML中唯一的内容.

@GionaF的想法让我得到了一个快乐(非常简单)的解决方案:

HTML

<!DOCTYPE html>
<head>
  <title></title>
  <LINK href="test2.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div>
      <img src="photo.jpg" alt="photo" />
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

CSS

img {
    max-width:100%;
    max-height:100%;
    position:absolute;
    top:0; left:0; right:0; bottom:0;
    margin:auto;
}
Run Code Online (Sandbox Code Playgroud)

Gio*_*ona 19

可以通过多种方式实现它,但我不能在不了解上下文的情况下"语义"(图像是页面的主要/唯一内容吗?它是在博客文章的中间吗?),所以我会去找一个div.


1. position:absolute;+margin:auto;

支持:crossbrowser

HTML

<html>
<body>
    <div id="container">
        <img src="your-image.jpg">
    </div>
</body>
</html>?
Run Code Online (Sandbox Code Playgroud)

CSS

html,body,#container {
    height:100%;
}
#container {
    width:100%;
    position:relative;
}
#container > img {
    width:100%;
    max-width:400px; /* real image width */
    position:absolute;
    top:0; left:0; right:0; bottom:0;
    margin:auto;
}
Run Code Online (Sandbox Code Playgroud)

演示


2. display:table;+ display:table-cell;+vertical-align:middle;

支持:IE8 +,所有其他浏览器 - 使用IE7后备(源1)(2)(3)

HTML

<html>
<body>
    <div id="container">
        <span> /* it's important that you use a span here
                  not a div, or the IE7 fallback won't work */
            <img src="your-image.jpg">
        </span>
    </div>
</body>
</html>?
Run Code Online (Sandbox Code Playgroud)

CSS

html,body,#container {
    height:100%;
}
#container {
    width:100%;
    display:table;
    *display:block; /* IE7 */
}
#container > span {
    display:table-cell;
    *display:inline-block; /* IE7 */
    vertical-align:middle;
    text-align:center;
}
#container > span > img {
    width:100%;
    max-width:400px; /* real image width */
}
Run Code Online (Sandbox Code Playgroud)

演示


3. background-size:contain;

支持:IE9 +,所有其他浏览器 - 带有供应商前缀(来源1)(2)

HTML

<html>
<body>
    <div id="container"></div>
</body>
</html>?
Run Code Online (Sandbox Code Playgroud)

CSS

html,body,#container {
    height:100%;
}
#container {
    margin:0 auto;
    max-width:400px; /* real image width */
    background:url(your-image.jpg) 50% 50% no-repeat;
    background-size:contain;
}
Run Code Online (Sandbox Code Playgroud)

演示


小心IE8如何渲染height:auto;,可能无法保持比例.


编辑:我刚刚意识到你写的" 没有调整图像的宽高比".如果你真的不想保持这个比例,那就更容易......但你真的是这个意思吗?