如何将具有z索引的<img/>居中?

时间:2015-10-24 16:09:47

标签: javascript html css image

我无法将图像居中,此刻,它停留在左侧。这个概念是当我点击图像时,图像的较大版本会弹出我们。

HTML:

<div class="photoposition" style="cursor:pointer" onclick="showImage('imagesinsurgent/in21.jpg');">
    <img src="imagesinsurgent/in21.jpg" class="scaledownlandscape"/>
    <p class="photogalleryp"></p>
</div>
<div id="largeImgPanel" onclick="hideMe(this);">
    <img id="largeImg" style="height: 100%; margin: 0; padding: 0;" />
</div>

CSS:

.photoposition{
    width: 250px;
    height: 250px;
    margin-left: 53px;
    float: left;
    position: relative;
}

.scaledownlandscape{
    width: 250px;
    object-fit: scale-down;
    display: block;
    margin: 0 auto;
}

.divspan{
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
}

#largeImgPanel {
    visibility: hidden;
    position: fixed;
    z-index: 100;
    top: 0; 
    left: 0;
    width: 500px; 
    height: 400px;
    background-color: rgba(100,100,100, 0.5);
    margin-top: 141px;
}

使用Javascript:

function showImage(imgName) {
    document.getElementById('largeImg').src = imgName;
    showLargeImagePanel();
    unselectAll();
}

function showLargeImagePanel() {    
    document.getElementById('largeImgPanel').style.visibility = 'visible';
}

function unselectAll() {
    if(document.selection) document.selection.empty();
    if(window.getSelection) window.getSelection().removeAllRanges();
}

function hideMe(obj) {
    obj.style.visibility = 'hidden';
}

1 个答案:

答案 0 :(得分:2)

#largeImgPanel 100%宽度并居中对齐内容

#largeImgPanel {
    visibility: hidden;
    position: fixed;
    z-index: 100;
    top: 0; 
    left: 0;
    right: 0;
    width: 500px; 
    height: 400px;
    background-color: rgba(100,100,100, 0.5);
    margin-top: 141px;
    text-align: center;
}

DEMO