简体   繁体   中英

Apply CSS only to inner-most element of same class as parent

I have an XML file that's structured as such (line numbers added for clarity).

1.  <myclass>
2.      <myclass>
3.          <myclass>
4.              <inner1>
5.              <inner2>
6.      <myclass>
7.          <myclass>
8.              <inner1>
9.              <inner2>
10.     <myclass>
11.         <inner1>
12.         <inner2>

I don't have control over the XML file, it's structured this way and I can't do anything about it. I need to apply a style to the inner most myclass elements (lines 3, 7, 10). All innermost myclass elements will have inner1 and inner2 children.

Applying a style, such as border to myclass , will cause stacked borders.

Currently, I'm preprocessing the XML by parsing through it and adding an innermost-myclass class to the parent of all inner1 elements.

I don't believe there is a way to do this without JS, though if you were open to it, there is a somewhat simple way of doing it in JS.

If it's of a fixed depth, you could check if the parent of the parent's class is also 'myclass'. If not, you could check if the div has children with 'myclass' or not.

The XPath-1.0 expression to select all innermost myclass elements which have inner1 and inner2 children is

//myclass[inner1 and inner2]

But according to this table for CSS/XPath equivalents , it is not possible to realize this in CSS3:

Goal                    CSS 3              XPath
All Elements            *                  //*
All P Elements          p                  //p
All Child Elements      p > *              //p/*
Element By ID           #foo               //*[@id=’foo’]
Element By Class        .foo               //*[contains(@class,’foo’)] 1
Element With Attribute  *[title]           //*[@title]
First Child of All P    p > *:first-child  //p/*[0]
All P with an A child   Not possible       //p[a]  <!-- This line would be relevant -->
Next Element            p + *              //p/following-sibling::*[0]

So, I guess you have to look for another way to realize this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM