Is it possible to select an element based on the c

2019-06-03 08:30发布

问题:

considering I have a single css file for my entire website (and that doing so is an usual technique), I was wondering if there is a way to select website-wide attributes like body (or any other attribute in fact) according to the current page using only css.

Something like

body:in('index.html') {
    some properties;
}

body:in('contact.html') {
    other properties;
}

Again, css only. I know the simple solutions using things like php, js, jquery...

回答1:

Selectors have no information about the document beyond what is presented in the DOM tree, and the DOM does not expose information about the page according to its file name, URL, or any other such properties.

Historically there was a @document at-rule for querying the current URL, but it was removed from the Conditional Rules Level 3 module. The most likely reason for this is the lack of cross-vendor implementations, as the only known implementation exists in Gecko, as @-moz-document. It's so bad, that the only uses for it that you'll spot in the wild are not to apply CSS based on a certain page, but solely as a CSS hack for Firefox.

As you've stated, the simplest workaround for this is to have each page apply a unique class to the html or body element and select according to that class, whether via hardcoding, or dynamically.



回答2:

you could add and id atribute to the body tag and style things inside it using:

body#contact div{
background:#376;
color:#857;
/*etc*/
}

more information about selectors in http://www.w3.org/TR/css3-selectors/