简体   繁体   English

水平和垂直居中img

[英]Centering img horizontally and vertically

I am trying to center an image vertically and horizontally inside a div. 我试图在div中垂直和水平居中放置图像。 The structure is as follows: 结构如下:

CSS: CSS:

.imgWrapper {
    background-color: #000;
    height: 100%;
    min-height: 480px;
    position: relative;
    text-align: center;
    -webkit-user-select: none;
    float: left;
}

.imgStg {
    cursor: pointer;
    display: block;
    font-size: 0;
    height: 100%;
    min-height: 402px;
    position: relative;
    text-align: center;
    width: 100%;
}

.imgStg img {
    display: inline-block;
    height: auto;
    max-height: 100%;
    max-width: 100%;
    vertical-align: middle;
    width: auto;
    text-align: center;
}

HTML: HTML:

<div class="imgWrapper" style="width: 724px;line-height: 601px;">
    <div class="imgStg"> 
        <img src="http://placehold.it/500x300" style="width: 500px;height: 300px;"/>
    </div>
</div>

*Note that the height of 601px is defined in a parent element *请注意,高度601px在父元素中定义

For some odd reason when I view the HTML file on localhost in both google chrome and firefox the image is aligned at the top of the div, not the center. 出于某种奇怪的原因,当我在google chrome和firefox中的localhost上查看HTML文件时,图像在div的顶部而不是中心对齐。

The fiddle: http://jsfiddle.net/5F3f3/1/ is showing correctly, why/what is causing it to display at the top on my machine? 小提琴: http : //jsfiddle.net/5F3f3/1/正确显示,为什么/是什么导致它显示在我的计算机顶部?

Screenshot of issue: 问题截图:

在此处输入图片说明

First of all height and line-height are not same. 首先高度和行高不一样。 Try this code, 试试这个代码,
CSS: CSS:

    .imgWrapper {
    background-color: #000;
    height: 100%;
    min-height: 480px;
    position: relative;
    text-align: center;
    -webkit-user-select: none;
    float: left;

}

.imgStg {
    cursor: pointer;
    display: block;
    font-size: 0;
    height: 100%;
    min-height: 402px;
    position: relative;
    text-align: center;
    width: 100%;
}

.imgStg img {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

HTML: HTML:

    <div class="imgWrapper" style="width: 724px;height: 601px;">
    <div class="imgStg"> 
        <img src="http://placehold.it/500x300" style="width: 500px;height: 300px;"/>
    </div>
</div>

I believe your CSS is correct. 我相信您的CSS是正确的。 Are you certain that it is being loaded correctly on localhost? 您确定它已在localhost上正确加载吗? I believe some browsers will give an error if the HTML is loaded via file:// scheme and the CSS is referenced via http:// scheme. 我相信,如果通过file://方案加载HTML并且通过http://方案引用CSS,则某些浏览器会给出错误消息。 Try referencing your CSS file as . 尝试将CS​​S文件引用为。 This will make the browser use the same scheme as the HTML that references it. 这将使浏览器使用与引用它的HTML相同的方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM