html - 悬停在第 n 个 child 上的问题

标签 html css css-selectors

我正在为网站创建一个新闻版 block ,每篇文章有 4 个图 block 。奇数方 block 的背景颜色为深蓝色,偶数方 block 的背景颜色为浅蓝色。 (暗光暗光)

现在我想添加一个 :hover 效果,使元素的颜色比其默认值稍微亮一些。因此,发生这种情况时,奇数和深蓝色的瓷砖颜色会稍微变浅,而偶数和浅蓝色的瓷砖颜色会变得更浅。

不过我对这种悬停效果有疑问。因此,如果我将鼠标悬停在第一个图 block (奇数)上,它也会在第三个(也是奇数)图 block 上添加 :hover 效果。

如何只对我悬停的那个执行此操作?

.tile-text {
        width: 100%;
        height: 25%;
        display: table;
        background: #337AB7;
        color: #EFEFEF;
    }
    
    .top-tiles a:nth-of-type(odd) .tile-text {
    	background: #304770;
    }
    
    .top-tiles:hover a:nth-of-type(odd) .tile-text {
    	background: orange; //just test-colors
    }
    
    .tile:hover .tile-text {
    	background-color: red; //just test-colors
    }
    
    .tile-text div {
    	display: table-cell;
    	vertical-align: middle;
    	font-size: 20px;
    }
    <section class="top-tiles">
		<a href="#">
			<div class="tile">
				<div class="tile-pic" style="background-image:url('');"></div>
				<div class="tile-text"><div>Sample text</div></div>
			</div>
		</a>
		<a href="#">
			<div class="tile">
				<div class="tile-pic" style="background-image:url('');"></div>
				<div class="tile-text"><div>Sample text</div></div>
			</div>
		</a>
		<a href="#">
			<div class="tile">
				<div class="tile-pic" style="background-image:url('');"></div>
				<div class="tile-text"><div>Sample text</div></div>
			</div>
		</a>
		<a href="#">
			<div class="tile">
				<div class="tile-pic" style="background-image:url('');"></div>
				<div class="tile-text"><div>Sample text</div></div>
			</div>
		</a>
	</section> 

作为附带问题,我还注意到如果我删除它:

.top-tiles:hover a:nth-of-type(odd) .tile-text {
    background: orange; //just test-colors
}

then .tile:hover .tile-text 仅适用于偶数 block 。为什么它不适用于奇数瓷砖?

谢谢!

最佳答案

尝试将您的 css 更改为:

.tile-text {
    width: 100%;
    height: 25%;
    display: table;
    background: #337AB7;
    color: #EFEFEF;
}

.top-tiles a:nth-of-type(odd) .tile-text {
    background: #304770;
}

.top-tiles a:nth-of-type(odd):hover .tile-text {
    background: orange; //just test-colors
}

.top-tiles a:nth-of-type(even):hover .tile-text {
    background-color: red; //just test-colors
}

.tile-text div {
    display: table-cell;
    vertical-align: middle;
    font-size: 20px;
}

关于html - 悬停在第 n 个 child 上的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32451383/

相关文章:

javascript - 在 PHP 中使用 Jquery Datepicker 显示日期时出错

javascript - 如何在 html Canvas 中添加镜头光晕效果

html - 容器内的中心图像

css - 如何在 Retina 屏幕上使用 CSS 媒体查询

php - 在多个数据库中插入数据

html - 将图像纵横比保持在列 div 内,同时保持相同的列高

html - 为什么 anchor 按钮超出包装边界?

html - 我可以使用纯 CSS 根据 URL 的获取参数设置链接样式吗?

CSS3 :unchecked pseudo-class

html - 仅当跨度位于 <a> 中且类不为 "folder"时,如何才能使我的 CSS 工作?