首页 > 解决方案 > 如何使 nth-child 停止影响所有元素

问题描述

我正在尝试创建一个 nth-child 来切换我添加的每个新元素的背景颜色,但是背景颜色针对我的所有元素。

@import url('https://fonts.googleapis.com/css?family=Lato&display=swap');
* {
  margin: 0;
  padding: 0;
  font-family: lato;
}

a {
  text-decoration: none;
}

.wrapper {
  display: flex;
  flex-direction: row;
}

.boxing {
  margin: 0 40px;
  position: relative;
  width: 400px;
  height: 580px;
  color: #333333;
  background-color: #ffffff;
}

.boxing img {
  width: 400px;
  height: 350px;
}

.box-text-area {
  width: 360px;
  height: 230px;
  padding: 0 0 0 40px;
  position: relative;
}

.boxing:nth-child(1) .box-text-area {
  background-color: #EDE0D2;
}

.box-text-area h4 {
  padding-top: 10px;
  font-size: 40px;
}

.box-text-area p {
  position: absolute;
  padding-top: 20px;
  left: 27%;
}

.appearing-asset {
  position: absolute;
  opacity: 0;
  background-color: rgba(0, 0, 0, .8);
  display: flex;
  justify-content: center;
  align-items: center;
  width: 360px;
  color: #ffffff;
  height: 350px;
  bottom: 0;
  padding: 0 20px;
  transition-duration: .4s;
  pointer-events: none;
}

.open-asset:hover .appearing-asset {
  opacity: 1
}
<!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>
</head>

<body>
  <div class="wrapper">
    <a href="#">
      <div class="boxing">
        <div class="box-text-area">
          <h4>8 Kitchen layout mistakes you don’t want to make</h4>
          <p>September 1, 2019</p>
        </div>
        <div class="open-asset">
          <img class="boxing-image" src="https://images.pexels.com/photos/584399/living-room-couch-interior-room-584399.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="">
          <div class="appearing-asset">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, reiciendis.</p>
          </div>
        </div>
      </div>
    </a>
    <a href="#">
      <div class="boxing">
        <div class="box-text-area">
          <h4>8 Kitchen layout mistakes you don’t want to make</h4>
          <p>September 1, 2019</p>
        </div>
        <div class="open-asset">
          <img class="boxing-image" src="https://images.pexels.com/photos/584399/living-room-couch-interior-room-584399.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="">
          <div class="appearing-asset">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, reiciendis.</p>
          </div>
        </div>
      </div>
    </a>
  </div>
</body>

</html>

标签: htmlcss

解决方案


希望这可以帮助你。

请尝试下面的CSS。

.wrapper a:nth-child(1) .box-text-area {
  background:EDE0D2;
}

:nth-child() pseudo-class计算同一父级下所有兄弟姐妹中的元素。它不只计算与选择器其余部分匹配的兄弟姐妹。类似地,:nth-of-type()伪类计算共享相同元素类型的兄弟姐妹,它指的是 HTML 中的标签名称,而不是选择器的其余部分

更新

codepen - https://codepen.io/prakashrajotiya/pen/ZEEEWNV?editors=1100


推荐阅读