Skip to content

Allow developers to opt out of !important CSS rules generated from theme.json #37590

Open

Description

@MarieComet

What problem does this address?

Currently, CSS rules generated from theme.json settings get !important automatically added.
It's fine for theme authors who need to ensure that their CSS rules are not overridden by plugins or so.
But as a theme developer, working at web agency, I don't need those !important. I control the scope of custom plugins.

What is your proposed solution?

My solution is to add a filter, to opt out of adding those !important to CSS, in the compute_preset_classes function.
eg : add_filter( 'compute_preset_classes_important', '__return_false' );

Activity

  1. MarieComet commented on Dec 22, 2021

    @MarieComet
    ContributorAuthor
    /**
     * Given a settings array, it returns the generated rulesets
     * for the preset classes.
     *
     * @since 5.8.0
     * @since 5.9.0 Added the `$origins` parameter.
     *
     * @param array  $settings Settings to process.
     * @param string $selector Selector wrapping the classes.
     * @param array  $origins  List of origins to process.
     * @return string The result of processing the presets.
     */
    private static function compute_preset_classes( $settings, $selector, $origins ) {
    	if ( self::ROOT_BLOCK_SELECTOR === $selector ) {
    		// Classes at the global level do not need any CSS prefixed,
    		// and we don't want to increase its specificity.
    		$selector = '';
    	}
    
    	$important_rule = apply_filters( 'compute_preset_classes_important', true );
    	$important = $important_rule ? ' !important' : '';
    
    	$stylesheet = '';
    	foreach ( self::PRESETS_METADATA as $preset_metadata ) {
    		$slugs = self::get_settings_slugs( $settings, $preset_metadata, $origins );
    		foreach ( $preset_metadata['classes'] as $class => $property ) {
    			foreach ( $slugs as $slug ) {
    				$css_var     = self::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
    				$class_name  = self::replace_slug_in_string( $class, $slug );
    				$stylesheet .= self::to_ruleset(
    					self::append_to_selector( $selector, $class_name ),
    					array(
    						array(
    							'name'  => $property,
    							'value' => 'var(' . $css_var . ')' . $important,
    						),
    					)
    				);
    			}
    		}
    	}
    
    	return $stylesheet;
    }
    
  2. overclokk commented on Dec 22, 2021

    @overclokk

    I think that the right place is to have a field in the theme.json itself instead of adding a filter.

  3. MarieComet commented on Dec 22, 2021

    @MarieComet
    ContributorAuthor

    I think it's fine in theme.json, but I don't know how to propose this change (code) :)

  4. added
    CSS Styling
    Needs Decision
    on Dec 22, 2021
  5. MarieComet commented on Dec 23, 2021

    @MarieComet
    ContributorAuthor

    Just thinking : a field in theme.json can't make possible to disable !important from child theme or plugin.
    PHP filter, yes.

  6. overclokk commented on Dec 23, 2021

    @overclokk

    Yes, not yet but a theme.json is a better place for users, not only for developers.

  7. oandregal commented on Dec 23, 2021

    @oandregal
    Member

    Hi Marie, I'd be interested in learning what issues does this causes for you so we can provide help.

    I also want to share the rationale for why we use this technique: we need to respect user choices at all times. There're blocks whose specificity is higher than 010, hence the presets classes attached by the user won't be applied if we don't use !important. See this thread for a longer review. If there's an alternative that fixes that issue and doesn't use !important I'd love to investigate it.

  8. glendaviesnz commented on Mar 16, 2022

    @glendaviesnz
    Contributor

    I'd be interested in learning what issues does this causes for you so we can provide help

    @jonschr, @webmandesign, @cbirdsong would any of you have a public theme in a repo, or be able to set one up, that demonstrates the issues around this - a classic theme, and a theme.json one if possible/applicable - and some reproduction steps for how to add content to a site running the theme to replicate the issues if needed. While exploring solutions it would be helpful to have some real-world scenarios to test against.

  9. webmandesign commented on Mar 16, 2022

    @webmandesign
    Contributor

    @glendaviesnz

    You can test with my Michelle theme (https://wordpress.org/themes/michelle/):


    Steps to reproduce the issue:

    1. With WordPress 5.9.2 install Michelle 1.2.0.
    2. Create a page and add a content from my gist.
    3. Publish the page and check how it looks like on front end. The font size in both columns should be equal. This is OK in WordPress 5.9.1 (unlike WP5.9). But for my theme the issue persist on smaller screens. (So you guys have technically fixed the issue probably for most cases in WP5.9.1. But the main issue we have is with !important styles.)
    4. Now update the theme to version 1.3.5 and check the page again. You'll see both columns have the same font size on all screen sizes.

    Results:

    I can only speak for myself. The issue was relatively fixed in WordPress 5.9.1 - meaning the font size is OK on large screens. But the real issue for me persist: WordPress still applies !important styles here.

    The theme is set with responsive typography and you can still see the issue when resizing the screen (with Michelle 1.2.0 and WordPress 5.9.1+).

    The only way around this is to remove !important rules applied by WordPress via the theme, or update the theme CSS code to use WordPress CSS variables naming.

    In my opinion, though, there should be no !important styles applied by WordPress. That's the main issue here and without it everything would be fine.

    If !important resolves some issue with theme.json themes, maybe go ahead there if that's really the only solution (although I still feel there must be a better way). But why messing up existing themes? Especially themes that promote using block editor?


    Finally, I think we should also make more distinction in "classic themes" terminology. Among "classic themes" there are themes that don't support Gutenberg editor and the ones that do. So, I suggest using this terminology:

    • Classic theme is a theme that does not include theme.json file and has no support for block editor. Meaning it was created for/around "Classic Editor". These themes seem not to be affected with the WP5.9 issue and that's why it is hard to trace - there is vast majority of this type of themes.
    • Block editor theme has no theme.json but declares support for block editor (such as font sizes, color palettes, wide alignment). These themes are affected with WP5.9 issue.
    • theme.json theme - for the lack of my knowledge, I use this term here as I don't know whether this means FSE theme yet or the theme can contain theme.json but not being FSE.

    This whole issue seems to be affecting block editor themes only.

  10. cbirdsong commented on Mar 16, 2022

    @cbirdsong

    I can set up a sample theme later this week, but for now I can describe some issues.

    For font sizes, responsive typography is a big one. Even in theme.json themes you can only accomplish it through a clamp() value, which is much less straightforward than media queries and has other issues. (see below)

    For block editor themes, another issue is that you can only supply pixel units for fonts in add_theme_support( 'editor-font-sizes'). Since I always use em or rem units and adjust them responsively , I would usually just pick a pixel value that looked correct-ish in the editor at common laptop resolutions, and then do the real thing with rem/em and clamp()/media queries in my CSS. The value I supplied was never intended to be used on the front end, and 5.9 overrode all my styles with it.

    However…

    This whole issue seems to be affecting block editor themes only.

    This is untrue! There are plenty of reasons you might want to override a value, even within a theme.json theme. For instance, this is a common pattern I use when declaring any value with min(), max(), or clamp():

    .has-large-font-size {
        font-size: 1.25rem;
        font-size: clamp(1.25rem, 1.25rem + 0.5vw, 1.8rem);
    }

    min(), max(), or clamp() are supported pretty well (~90% worldwide), but 10% is a lot pf people, and declaring the static font-size value before the clamp() one ensures those visitors still get a reasonable version of your design. The fact that you can only declare a single !important value in theme.json makes it impossible to offer this straightforward bit of progressive enhancement.

    This only gets into issues created for font sizing. This approach creates many similar problems in other areas (most notably colors), which like this leads me to agree here:

    In my opinion, though, there should be no !important styles applied by WordPress. That's the main issue here and without it everything would be fine.

    !important should be treated as a “break glass in case of emergency” tool. Using it correctly requires a CSS author to consider how it would affect the project as a whole, but this just slaps it on everything without judgement, resulting in the inability to use CSS as designed to handle responsive typography, dark mode and even changing link colors on hover/focus, which is as fundamental and basic as it gets.

    It should absolutely not be applied retroactively to pre-5.9/theme.json v2 themes, and I'd strongly suggest it not be applied at all, no matter how much easier it makes the job of the editor authors.

  11. webmandesign commented on Mar 16, 2022

    @webmandesign
    Contributor

    @cbirdsong

    For block editor themes, another issue is that you can only supply pixel units for fonts in add_theme_support( 'editor-font-sizes'). Since I always use em or rem units and adjust them responsively , I would usually just pick a pixel value that looked correct-ish in the editor at common laptop resolutions, and then do the real thing with rem/em and clamp()/media queries in my CSS. The value I supplied was never intended to be used on the front end, and 5.9 overrode all my styles with it.

    Indeed, I experience the same issue here, but this was true also pre-WP5.9 unfortunately. I approach it similarly as you do. I kind of made peace that add_theme_support( 'editor-font-sizes' ) will not be updated to work with relative units or even with CSS variables.

    This is untrue! There are plenty of reasons you might want to override a value, even within a theme.json theme.

    Sorry, I don't have enough experience with theme.json themes. But I can see your point. I hope this will be fixed in the future somehow. The issue I can see here is that for some reason it looks like CSS is being replaced with JSON in WordPress themes. I'm skeptic this approach would ever provide the same flexibility as CSS does... But I have to dig deeper into theme.json theme development to see what it's capable of - currently it's very early stage to match classic themes flexibility.

    However, with theme.json theme I think I would approach your issue via CSS variables named according to WordPress naming convention. Basically, I'd updated your CSS code:

    /* From this: */
    .has-large-font-size {
    	font-size: 1.25rem;
    	font-size: clamp(1.25rem, 1.25rem + 0.5vw, 1.8rem);
    }
    /* To this: */
    body {
    	--wp--preset--font-size--large: clamp(1.25rem, 1.25rem + 0.5vw, 1.8rem);
    	/**
    	 * You should be able to use @support now for backwards compatibility,
    	 * or simply revert to @media query approach or do whatever you like with
    	 * the CSS variable.
    	 * This should work with core's `!important` without any issue I think.
    	 */
    }

    By setting up the CSS variable I think you can do the whole responsive typography spiel to your liking and you don't even need to declare styles for .has-large-font-size class. But this is just from top of my head and I haven't tried this ;)

  12. jonschr commented on Mar 16, 2022

    @jonschr

    @glendaviesnz The remaining issues for me are, like others, around responsive styles. I use a sass mixin for smooth scaling up and down font sizes between a desktop size and a mobile size, and the !important declaration overrides it, resulting in a normal experience on desktop and incorrectly-sized text on mobile for any text that's set to small, large, xlarge, etc.

    For me, however, this is the same whether I'm in an add_theme_supports theme or a theme.json theme. The !important declaration slightly exacerbates this.

    I'm not a huge fan of using !important declarations in general, but in this particular case I don't actually have a huge problem with its use, as the user is setting a size in the Gutenberg UI and !Important helps to enforce that choice, overriding defaults that in some cases probably do need to be overridden.

    My biggest thing would probably be that theme developers don't really have a recommended way to add support for different sizing on mobile that would inherit the !important declaration (I see some suggestions up above that I haven't tried, but haven't seen similar stuff in the documentation).

  13. cbirdsong commented on Mar 16, 2022

    @cbirdsong

    By setting up the CSS variable I think you can do the whole responsive typography spiel to your liking and you don't even need to declare styles for .has-large-font-size class. But this is just from top of my head and I haven't tried this ;)

    This is true, but that doesn't set a progressively enhanced fallback for browsers that don't support custom properties.

    More importantly, it doesn't fix all the existing themes that don't have anyone actively developing them and assumed no one would be coming through and adding "!important" to these classes.


    I'm not a huge fan of using !important declarations in general, but in this particular case I don't actually have a huge problem with its use, as the user is setting a size in the Gutenberg UI and !Important helps to enforce that choice, overriding defaults that in some cases probably do need to be overridden.

    Actually, these are !important-ed with theme-supplied font size presets and custom font sizes disabled.

    For reference, when starting with this:
    	add_theme_support( 'disable-custom-font-sizes' );
    	add_theme_support( 'editor-font-sizes', array(
    		array(
    			'name' => __( 'Small', 'block-editor-theme' ),
    			'size' => 12,
    			'slug' => 'small'
    		),
    		array(
    			'name' => __( 'Medium', 'block-editor-theme' ),
    			'size' => 16,
    			'slug' => 'medium'
    		),
    		array(
    			'name' => __( 'Large', 'block-editor-theme' ),
    			'size' => 24,
    			'slug' => 'large'
    		),
    	) );
    The CSS generated looks like this:
    body {
      --wp--preset--font-size--small: 12px;
      --wp--preset--font-size--medium: 16px;
      --wp--preset--font-size--large: 24px;
    }
    .has-small-font-size {
      font-size: var(--wp--preset--font-size--small) !important;
    }
    .has-medium-font-size {
      font-size: var(--wp--preset--font-size--medium) !important;
    }
    .has-large-font-size {
      font-size: var(--wp--preset--font-size--large) !important;
    }
  14. glendaviesnz commented on Mar 17, 2022

    @glendaviesnz
    Contributor

    Thanks for the extra details and sample themes, everyone. I am just trying to get a couple of other unrelated PRs finished off and will hopefully have a closer look at this tomorrow.

  15. 20 remaining items

  16. cbirdsong commented on Jul 15, 2024

    @cbirdsong

    In that case, it could also be more specific and use background-color instead of stomping all over every background- property with the background: shorthand. Good blog post: https://csswizardry.com/2016/12/css-shorthand-syntax-considered-an-anti-pattern/

  17. eric-michel commented on Jul 16, 2024

    @eric-michel

    I am becoming increasingly concerned that there is an attitude of "everything should be done in the editor" as Gutenberg continues to grow. I have seen comments from contributors that make it very clear that consideration of theme CSS is not a priority during development. And as Gutenberg continues to offer more controls for various styling features, so does its CSS footprint. Each update introduces new conflicts that developers have to fight, sometimes very unnecessarily (see #60922).

    Don't get me wrong, I absolutely love that Gutenberg creates an easy interface for creating complex content, but it can't be everything to everybody. There has to be room for theme customization. I know a lot of us have belabored this point, but it's a huge ongoing issue.

  18. nabrown commented on Dec 9, 2024

    @nabrown

    I've just come across this issue, where once I introduced theme.json into an otherwise "classic" theme (making managing a custom palette much easier in many ways) a few local overrides I had for the .has-<color>-background classed were being overridden with !important on the WP style rules. At the very least, yes -- these rules should only apply a background-color and not use the background shorthand. A big improvement would be to use one of the strategies above to eliminate the use of !important. Or, allow opt-out via theme.json. For those of us developing bespoke themes for a single client (not for distribution) this would be very helpful.

  19. removed their assignment
    on Dec 9, 2024
  20. dgrumbler commented on Mar 10, 2026

    @dgrumbler

    I've also come across this issue and just wanted to flag that it's also an accessibility issue as it prevents users from being able to modify styling using a browser plugin to adapt a site to their individual preferences. For example a user with color deficiency or low vision might override page colors to enforce certain colors or high contrast. See here for more information https://dev.to/alvaromontoro/using-important-in-css-75c

  21. webmandesign commented on Mar 10, 2026

    @webmandesign
    Contributor

    Hi @dgrumbler, I've released Global Styles Mods plugin in the past. It may still work just fine resolving your issue.

  22. Lumne commented on Jun 23, 2026

    @Lumne

    I just came across the issue for a hybrid theme site and am surprised that !important is being used like this in WordPress. It has long been considered best practice to avoid liberal use of !important. I also highly recommend avoiding the specificity battle by using :where more like others recommended years ago in this thread. A way to opt out of the use of !important would be a sensible compromise since it seems unlikely !important will be removed for all by default.

  23. ramonjd commented on Jun 23, 2026

    @ramonjd
    Member

    3 years after this comment CSS @layers has more support, but not much.

    I agree a rethink of how WordPress CSS inheritance work is overdue. I was hoping @layers would be our saviour one day 😄

    Whichever way it's done backwards compat would be an issue I think - it's not recommended but I imagine there'd be a lot of themes overwriting classes, expecting them to be there. Maybe a CSS refactor would be opt-in or something.

  24. eric-michel commented on Jun 26, 2026

    @eric-michel

    Based on caniuse stats, it looks like @layers has achieved roughly the same adoption as :where - over 96% of users using tracked browsers in the U.S. and over 97% globally.

    I wonder if it makes sense to start the refactor to use @layers now. It will likely take months/years of discussion and workshopping to rework the block editor's CSS and style engine. During that time, adoption will rise even higher.

  25. ramonjd commented on Jun 30, 2026

    @ramonjd
    Member

    I wonder if it makes sense to start the refactor to use @layers now. It will likely take months/years of discussion and workshopping to rework the block editor's CSS and style engine.

    I like your thinking 😄 Even proposing a direction and backwards compat route would be a start. Months, if we're lucky. Years, I hope not 😄

  26. ramonjd commented on Jun 30, 2026

    @ramonjd
    Member
  27. cbirdsong commented on Jun 30, 2026

    @cbirdsong

    I would love for any big refactoring/restructuring to take this issue into account 🙏

    The editor's CSS still desperately needs a coherent structure and strategy.

  28. eric-michel commented on Jun 30, 2026

    @eric-michel

    @cbirdsong

    I would love for any big refactoring/restructuring to take this issue into account 🙏

    #54033

    I could probably come up with a dozen issues submitted by just the two of us that I'd like considered in any major CSS rework 😅

    I'd love to see a discussion thread like #61810 dedicated to a holistic conversation about what a wholesale CSS rework should incorporate. If @layers is actually on the table, so many blocks and systems will need to be touched that it makes sense to consider broader improvements at the same time.

  29. ramonjd commented on Jul 1, 2026

    @ramonjd
    Member

    I would love for any big refactoring/restructuring to take this issue into account 🙏

    Some good ideas there, thanks for sharing. Sorry I missed it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CSS StylingNeeds Decision[Type] Enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions