垂直对齐悬停img

时间:2014-09-02 17:52:18

标签: javascript jquery html css image

我有一个宽度相同但高度不同的图像网格。

在悬停图像时,我想显示两个不同的链接,以获取图像和作者的信息。

问题是我无法在图像上垂直链接:/

HTML:

                <div class="item">
                    <div class="img-work">
                        <img src="img/grid1.jpg" alt="" class="img-grid">
                        <a href="#" class="zoom"">
                            <img src="img/hover-item.png" alt="">
                        </a>
                        <a href="#" class="info">
                            <img src="img/hover-info.png" alt="">
                        </a>
                    </div>
                </div>

CSS:

div.img-work a.zoom {
   left: 31%;
   position: absolute;
   top: 27%;
   visibility: hidden;
   width: 38px;
}
div.img-work a.info {
   left: 50%;
   position: absolute;
   top: 27%;
   visibility: hidden;
   width: 39px;
}

jQuery的:

    $('div.img-work').hover(function() {
        $(this).children('a').css('visibility', 'visible');
        $(this).children('img').css('opacity', '0.5');
    }, function() {
        $(this).children('a').css('visibility', 'hidden');
        $(this).children('img').css('opacity', '1');
    });

你无法看到我不知道如何垂直对齐这些链接。任何提示都会很感激。提前谢谢

3 个答案:

答案 0 :(得分:1)

这是一个CSS解决方案:http://jsfiddle.net/08vorn1s/

图像在其容器内垂直和水平居中。如果图像需要底部对齐,您可以轻松调整代码。

HTML:

<div class = "grid">
    <div class = "row">
        <div class = "cell">
            <img src = "http://placehold.it/150x150 " />
            <div class = "links">
                <a href = "#">Info</a>
                <a href = "#">Author</a>
            </div>
        </div>
        <div class = "cell">
            <img src = "http://placehold.it/150x170 " />
            <div class = "links">
                <a href = "#">Info</a>
                <a href = "#">Author</a>
            </div>
        </div>
        <div class = "cell">
            <img src = "http://placehold.it/150x200 " />
            <div class = "links">
                <a href = "#">Info</a>
                <a href = "#">Author</a>
            </div>
        </div>
    </div>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
}

body {
    padding: 10px;
}

.grid {
    display: table;
    width: 100%;
}

.grid .row {
    display: table-row;
}

.grid .row .cell {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    position: relative;
}

.cell > .links {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    display: none;
}

.cell:hover > img {
    opacity: 0.5;
}

.cell:hover > .links {
    display: block;
}

答案 1 :(得分:0)

您是否尝试过像position: relative那样设置您的媒体资源?您可能还希望根据图片大小调整lefttop CSS属性。

答案 2 :(得分:0)

您的.item元素需要position: relative;,并且您的重叠元素(.info)需要:

position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
display: block;