Html CSS-选择下一个元素

Html CSS-选择下一个元素,html,css,selector,Html,Css,Selector,我不知道该怎么解释,但是。。。 我想选择一个元素,但它与另一个元素相差很远 像这样: <div class="image-div"> <img src="forest.png" class="image forest"> </div> <p> I want to change the color of this text if the image there ^ is "forest", which I'll change with

我不知道该怎么解释,但是。。。 我想选择一个元素,但它与另一个元素相差很远

像这样:

<div class="image-div">
    <img src="forest.png" class="image forest">
</div>
<p>
    I want to change the color of this text if the image there ^ is "forest", which I'll change with JS
</p>

.image.forest [some selector idk] p {
    color: red;
}
.image.train [some selector idk] p {
    color: blue;
}
您需要从到,但是从到会带来一个问题:没有CSS选择器允许您引用DOM树中较高的元素,即没有子到父选择器

相反,您可以将.forest类应用于

HTML:

您需要从到,但是从到会带来一个问题:没有CSS选择器允许您引用DOM树中较高的元素,即没有子到父选择器

相反,您可以将.forest类应用于

HTML:


为什么不在森林图像后面的p标记中添加一个类呢

.forest + p {
    color: red;
}

为什么不在森林图像后面的p标记中添加一个类呢

.forest + p {
    color: red;
}

如果对你有用的话,你可以这样重写

<div class="image-div">
    <img src="forest.png" class="image forest">
</div>
<p class="forest-paragraph"></p>

.forest-paragraph {
     color: #000;
}

如果对你有用的话,你可以这样重写

<div class="image-div">
    <img src="forest.png" class="image forest">
</div>
<p class="forest-paragraph"></p>

.forest-paragraph {
     color: #000;
}

既然你已经在使用JS了,为什么不使用它来将一个类应用到p上呢?那么你就可以使用类似img.forest{}的css了。。。p、 林{}我没有想到我会用JS来改变这个问题,因为你已经在使用JS了,为什么不使用它来同时将一个类应用到p-那么你就可以使用类似img.forest{}的css。。。p、 森林{}我没想到这个LOL类可能会改变,任何标记之后。森林应该反映风格,他可能有其他图像与其他类一起包装,例如沙漠或.sea类可能会改变,任何标记之后。森林应该反映风格,他可能会有其他的图片被包装在一个带有其他类的文件中,例如.desert或.Sea似乎不是父类。OP似乎不是问如何实现父类选择器。我已经澄清。似乎不是父类。OP似乎不是问如何实现父类选择器。我已经澄清。