html - 纯 CSS : Show image2 above/over/on top image1 on hover

标签 html css image hover

SOLVED FIDDLE :

我不知道如何在悬停时在我当前可见图像(一个)上方/上方显示一个图像(两个)。

HTML:

<img class="two" src="img/2.png" alt="bulb">
<img class="one" src="img/1.png" alt="me">

CSS:

.one {
display: block;
margin: 0 auto;
padding-top: 50px;
}

.two {
opacity: 0;
}

.one:hover .two {
opacity: 1;
}

我做错了什么?

最佳答案

编辑:如果你想在第一张图片下方显示另一张图片,那么你需要更改 DOM,因为 CSS 无法选择前一个元素,但它可以选择相邻的图片,你使用的是 .one :hover .two 将在 hover 上选择具有类 .two 的元素嵌套在具有类 .one 的元素下,但由于元素是相邻的,你可以使用下面的选择器,但是注意你需要改变DOM中的元素顺序。

.one:hover + .two {
    opacity: 1;
}

Demo


我假设 Above 意味着悬停时你想交换图像,所以如果这是你想要的而不是通过将图像设置为 position: absolute; 使用 CSS 定位技术它们嵌套在 position: relative; 容器下。

Demo

div {
    position: relative;
}

div img { /* Setting images to absolute */
    position: absolute;
    top: 0;
}

div img:nth-of-type(2) { /* Initially hiding image 2 */
    opacity: 0;
}

div:hover img:nth-of-type(1) { /* On hover of div we hide 1st image */
    opacity: 0;
}

div:hover img:nth-of-type(2) { /* On hover of div we show 2nd image */
    opacity: 1;
}

您还可以添加 transition 属性以在 hover 时平滑地交换图像

Demo

div img {
    position: absolute;
    top: 0;
    -moz-transition: all .5s;
    -webkit-transition: all .5s;
    transition: all .5s;
}

关于html - 纯 CSS : Show image2 above/over/on top image1 on hover,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626565/

相关文章:

javascript - 如何内联页面布局多个部分需要的JS?

html - 使用检查器窗口进行填充

android - 如何在 android 的 sqlite 数据库中存储(位图图像​​)和检索图像?

html - 下拉组合框不对齐

c# - 使用 agility pack 解析 html

android - HTML5 - 安卓屏幕尺寸

html - 如何实现横向卡片样式

javascript - 更改文字颜色

image - Beamer:如何将图像显示为分步图像

html - 在 TinyMCE 中设置数据 URI