Immediate children css, and only those

2019-07-28 18:45发布

What I'm trying to achieve sounds really simple, but is not. I don't even know if I can accomplish what I'm trying todo.

Ok so we got our element with the classname .parent, .parent got two div children, one is immediate and the other one is put into the first one like so:

<div class="parent">
  <div>First child
    <div>Second child</div>
  </div>
</div>

Targeting the first child should be as simple as:

.parent > div {
  color: green;
}

but it isn't, as "Second child" also get affected.

Is this achieveable?

Sidenote: Some CSS-properties like "color" is inheriting from parents, even though the element does not got the direct style. I guess this is what causing the issue. But still, I don't want it to cascade.

4条回答
Anthone
2楼-- · 2019-07-28 18:54

No, you can't.

CSS color property is Inherited by default.
It's not possible to do it in the way you want.

But more important: It's not an ISSUE, it's the way that supposed to be.
Remember: CSS => Cascade Style Sheet.

Now, for your question... the simple, easy and the right way to "solve" this... is the one that already told you @Bhojendra Nepal in his previous answer.

Edit:

Another option would be wrapping that flying text in a span tag.. or similar:

.parent > div > span {
  color: green;
}
<div class="parent">
  <div>
    <span>First child</span>
    <div>
      <span>Second child</span>
    </div>
  </div>
</div>

查看更多
我命由我不由天
3楼-- · 2019-07-28 19:17

When you use div > p it means that Selects all p elements where the parent is a div element

But if you set one element with a property, all children will inherit that property if you don't override it. For example:

<div class="parent">
  <div>First child
    <div>Second child</div>
  </div>
</div>

In your case, all divs will have the property color:green by inheritance. If you want to change the property of the second div you have to do the following: div.parent div div { color: red }. This means Select all div which parent is a div which parent is a div with class "parent".

This is how stylesheets work.

查看更多
放我归山
4楼-- · 2019-07-28 19:18

The css is in cascade so the changes you do to an element effect the children. You could, however put a css class to the second child to override the css.

查看更多
Fickle 薄情
5楼-- · 2019-07-28 19:19

Parent element color is inherited to children element. First set div color and then use direct children's color:

.parent div{
  color: #000;
  }
.parent > div {
  color: green;
}
<div class="parent">
  <div>First child
    <div>Second child</div>
  </div>
</div>

查看更多
登录 后发表回答