Selecting a sibling of a parent

2020-04-30 03:32发布

问题:

I've got this HTML:

<font>
   <b>
      <a href="profile/user">user</a>
   </b>
   <font>message</font>
</font>

I know the font tag sucks, but they wanted font tags so I put font tags. I can select the user's name with a[href*="user"] but I want to be able to select the font containing the message, too. Is that possible with CSS?

回答1:

You cannot select the parent with CSS - you might find this an interesting read on the topic: Why we don't have a parent selector. However, you can do one of the following:

1. Use a bit of JavaScript

2. Change your HTML to

<font>
   <a href="profile/user"><b>user</b></a>
   <font>message</font>
</font>

and you can do this:

a[href*="user"] + font { /* YOUR STYLES HERE */ }


回答2:

You cannot move a level up to an element´s parent using CSS.