Search code examples
htmlcsscss-specificity

Set Default Font Style for Specific Tags in Portion of Page


What is the best, most maintainable and readable approach to setting a CSS property as the default for given tags in a portion of a page with low specificity. Currently, I have a page which takes the global default font styling from a html selector in a separate global stylesheet. There is a large portion of my page (which has the class dash) which I want to have a different default font style.

The main issue with just setting .dash h1 { font.... } is that this has very high specificity. Every time I want to set a font style for an element which is a descendant of .dash, I need to refer to .dash. Since I am working around a modular design, where each component is developed independently, this is a very bad idea. An even worse solution would be to set !important or to use an ID, for obvious reasons. Obviously, we don't run into this issue when setting fonts for html h1, or any other tag since all tags have lower specificity than classes.

Is there a simple low-specificity approach to setting a CSS property for tags which are descendants of an element high up in the DOM, selected by a class such that it can be overwritten by applying font properties to and element selected by another class?


Solution

  • Based on Harry Roberts article http://csswizardry.com/2014/07/hacks-for-dealing-with-specificity/#safely-increasing-specificity, I applied the same class repeatedly in order to increase the specificity of that selector above that applied to the portion (which itself is set simply as .portion-class tag).

    See:

    Note that I was, of course, wrong to think that the location of elements in the DOM was affecting the specificity.