我想定位具有photo
类的图像。但是,nth-child
在该元素上不起作用。我在寻找许多解决方案,但无法解决!
.container {
height: 100vh;
position: relative;
}
.irene {
position: absolute;
top: 10%;
left: 10%;
width: 60vw;
}
.irene-img {
position: relative;
}
.irene-img::after {
content: ' ';
z-index: -1;
position: absolute;
left: 5%;
top: 5%;
width: 100%;
height: 100%;
border: 5px solid #2ebce2;
}
.irene-title {
position: absolute;
left: -10%;
top: -10%;
color: rgba(0, 0, 0, 0.4);
font-size: 10rem;
}
.irene-title span {
font-size: 5rem;
}
.single__detail__spec {
position: absolute;
font-size: 2rem;
line-height: 2;
top: 35%;
right: 10%;
color: rgba(0, 0, 0, 0.8);
}
.single__detail__spec span {
font-weight: bold;
}
.single__detail__saying {
position: absolute;
width: 400px;
font-size: 2rem;
line-height: 2;
bottom: 5%;
right: 5%;
color: rgba(0, 0, 0, 0.8);
}
.photo {
position: absolute;
width: 400px;
}
.photo:nth-child(1) {
left: 0;
top: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<base href="https://raw.githack.com/baeharam/Redvelvet-Fansite/master/html/">
<link rel="stylesheet" href="../css/default.css">
</head>
<body>
<div class="container">
<div class="irene">
<div class="irene-img">
<img src="../images/about-irene.jpg" alt="">
</div>
<p class="irene-title">IRENE <span>배주현</span></p>
</div>
<p class="single__detail__spec">
<span>생일.</span> 1991.03.29<br/>
<span>별명.</span> 배추, 현이, 엔딩요정<br/>
<span>취미.</span> 다리미질, 빨래<br/>
<span>혈액형.</span> A형
</p>
<p class="single__detail__saying">
"lorem ipsum"
</p>
</div>
<img class="photo" src="../images/photo-irene1.jpg" alt="">
</body>
</html>
为什么nth-child
中的photo
不起作用?如何处理?
答案 0 :(得分:0)
我认为您在nth-child和nth-of-type之间感到困惑
nth-child(n)
:选择同一父元素中n-1
元素之后的匹配元素,它不在乎那些元素是否与同一选择器匹配,只在意位置。>
nth-of-type(n)
:选择n-1
元素之后的匹配元素,该元素与同一父对象中的相同选择器匹配。
有两种可能的解决方案
img:nth-child(2)
img:nth-of-type(1)
答案 1 :(得分:0)
问题已经回答,但我想添加一些内容: .photo:nth-child(1)通常写为.photo:first-child。
如前所述,在这种情况下它不起作用,因为具有“照片”类的元素不是其父级的第一个子级。选择器.photo:first-child(无论如何都是正确的选择)以及选择器.photo:nth-child(1)将查找具有.photo类的元素,该类是其父级的第一个孩子。如果该类中没有元素,同时又是其父母的第一个孩子,则该样式将不适用。
如果要按类型选择(例如),请选择该类附带的第一个元素,无论其位于父元素的位置如何,都应使用选择器.photo:nth-of-type(1)。
如果要根据元素到其父元素的位置选择元素,则应为.photo:nth-child(2),因为类.photo的元素是相对于其父元素的第二个元素。
这里是对:nth-child(n)的指南,我发现这很有解释性。 https://css-tricks.com/useful-nth-child-recipies/
这里是类型:{nth-of https://css-tricks.com/almanac/selectors/n/nth-of-type/的指南,该指南也很容易理解。希望我能帮上忙!