[HN Gopher] CSS's !important was added for one reason only ___________________________________________________________________ CSS's !important was added for one reason only Author : mmastrac Score : 314 points Date : 2022-03-21 17:40 UTC (5 hours ago) (HTM) web link (twitter.com) (TXT) w3m dump (twitter.com) | iforgotpassword wrote: | I agree with that tweet there: | | > If you need to set font-sizes with !important you also don't | understand the cascade | | If law requires you to make certain text a certain size, just do | so. | | Without any more background information, this explanation for | !important doesn't make any sense. | zerocrates wrote: | I don't doubt the explanation but agree it doesn't totally make | sense: an !important-set font-size is not really any more | "guaranteed" than another one, as it can just be overridden | with another more-specific or later-appearing !important style. | So you still have to look at all the styles to be sure you're | complying, and if you're going to do that then you might as | well just not use !important at all. | | Though I'll admit that once you have your "mandatory" size | style as !important you'd only have to look at the other | !important ones to be sure, so there's something to it. | | Of course there's lots of perfectly reasonable uses of | !important now: dealing with other peoples' uses of !important. | amalcon wrote: | I wasn't there, but putting myself in the headspace of someone | who was and may have had to comply with that law: There are | things outside of the individual control of the designer that | can override everything _except_ !important. The most obvious | example is non-!important rules in user stylesheets. | | Today it's obvious that overriding a font-size with a user | stylesheet is a bit of an extraordinary measure. You're | unlikely to have any legal issues based on somebody shrinking | your text using one. This may not have been obvious in the | meetings in which CSS was being designed: it's plausible that I | might think user stylesheets would be all over the place and | have unpredictable effects, including shrinking disclaimers or | whatever. On the other hand, putting !important in a user | stylesheet could've seemed like an extraordinary measure even | then. | | But again, I wasn't there. I'm just making semi-educated | guesses. | manquer wrote: | There is no law for the designer of CSS system. Only the | developers who build UI have any liability to comply with the | law. As long as CSS allowed them to render the required font- | sizes there was no reason for them build breaks to the | cascading to "comply with law", perhaps it makes it easier | for developers with this feature to comply to the law, but | there was no requirement to make it easy . | tshaddox wrote: | Still, it doesn't make sense why _US law_ makes it necessary | to have this feature, but any other business or design | requirement wouldn't make this feature necessary. Surely if | the CEO or designer says "this text must be 24px" that's not | any different from the implementer's perspective as a law | which says the same thing. This whole thing doesn't really | add up. | amalcon wrote: | It's different from the implementer's perspective because | the implementer can go back to the CEO (maybe indirectly) | saying "I can make that work 80% of the time, but it just | can't be done for the 20% of users who have expressed a | preference to the contrary". In your example the CEO gets | the option to say "OK, make it work most of the time". In a | compliance situation, the CEO is legally obligated to can | the whole project, find someone willing to put the text in | a JPEG with the attendant accessibility issues, or some | other draconian maneuver. | gowld wrote: | If you send me a government mandated form, and I scrible | on it, you aren't liable for anything. The only potential | concern is if the content is deployed through a framework | like Wordpress that might add CSS. | cosmie wrote: | > This whole thing doesn't really add up. | | If the originally purported intent had carried through to | the specifications, it adds up in a sense. If !important | overrides indicated an explicitly set formatting/sizing for | compliance/legal reasons, implementers touching it without | any historical context would know at a glance what it | signified and that it shouldn't be touched lightly without | explicit approval. And when the implementer updates the | stylesheets to use 24px text on a page based on direction | from the CEO/designer and the element with an !important | override stays at 26px, the implementer can point to the | !important override as the cause and confirm if the person | requesting the change has confirmed legal/compliance | approval to change that one as well. Even if the parties | involved in the change (the designer, CEO, or implementer) | aren't familiar with the compliance reason for the | override's origins, the fact that it's there is a known | flag that changes can lead to potential violations and | costs/fines and need to be properly vetted for approval. | | It would also make it easier to go in and update the | stylesheets to comply with changes in compliance/legal | requirements, as you can easily search through the styles | for !important flags and find all the spots that need | reviewed for potential change needs. | | That said, its use in practice is completely different than | this purported rationale for the flag's existence, and | !important is sprinkled so cavalierly in existing codebases | to crudely but effectively get a desired effect that the | above situation is impossible at this point and the | original rationale is moot. | btown wrote: | > You're unlikely to have any legal issues based on somebody | shrinking your text using one. This may not have been obvious | in the meetings in which CSS was being designed: it's | plausible that I might think user stylesheets would be all | over the place and have unpredictable effects. | | Someone predicting "stylesheets all over the place" would | have been exactly right, though - practically every single | news page on the Internet has questionably-sourced ads, | Facebook like buttons, Twitter embeds, and | chat/discussion/engagement widgets, all of which have custom | stylesheets. The only saving graces come from frequent use of | iframes for isolated embeds (which will become less common | now with cookie restrictions!), stylesheets well-engineered | by well-funded corporations to have every rule prefixed by a | custom and dedicated class name for compatibility, and | preprocessors and CSS-in-JS that would make that latter | approach viable. | | Now imagine a world where you're a site operator, !important | doesn't exist, and you cannot trust that a site component | provider will not install a global CSS rule that will break | your legal or branding requirements, with no real way for you | to work around it if they do, without unmaintainable | specificity boosters for your own components. You simply | won't use that site component provider unless it's well- | vetted. Which means that there's significantly less | innovation on the Internet, because "nobody ever got fired | for embedding IBM CSS" becomes an actual thing to think | about. !important becomes the escape hatch that the web | needs. | francisofascii wrote: | CSS !Important is a nice fail safe or safety valve for | emergencies. It is good design to have safety valves in a system. | Sure, you should not be encouraged to use it under normal | circumstances. As with other fail safe features, it is meant for | extreme scenarios you can sometimes predict, but more importantly | for reasons you CANNOT predict. So this tweet arguing that it is | meant for one reason is invalidating why it is good design. | Waterluvian wrote: | I think one concept that's slowly coming into focus for me is | just how many engineers want you to experience _their_ experience | and spend your time reveling at how clever _their_ stuff is. As | if they think you wake up and want to do CSS work. CSS is not the | goal. The website I'm building isn't even the goal. The goal is | to solve some problem. | | Everything that I have to do to solve that problem is an | unfortunate (but inevitable) reality. But let's be clear: the | goal is to minimize as close to zero, how much time you have to | spend doing these things. | | CSS, like all code, is a total liability. I want to spend as | little time designing and writing it as possible. Which is why I | hate CSS: it demands you know the exact current and future | (hahahaha) structure of your webpage. `!important` is not some | panacea, but I cackle at the ignorance of suggesting that the | user is wrong for misusing it. | [deleted] | edgyquant wrote: | Boy this is exactly how it felt to me as a junior. I was just | sure it was the fault of everyone else's configuration that was | the problem, not mine. The hardest lesson a junior has to learn | is that the customer is always right. No one cares if your | program runs perfectly on your machine, because of course it | does, it has to run perfectly on every machine. | tiborsaas wrote: | > Which is why I hate CSS: it demands you know the exact | current and future (hahahaha) structure of your webpage. | | Replace _structure_ with users, environment or other factor you | can 't control and you'll realize you must hate every other | aspects of development :) | calibas wrote: | Misuse literally means "the wrong or improper use of | something", so your statement also suggests the user is | wrong... | meerita wrote: | For those tired of dealing with any OOCSS variant, you can go | full functional css http://minid.net/2019/04/07/the-css- | utilitarian-methodology/ and say goodbye to !important | dredmorbius wrote: | https://nitter.kavin.rocks/stevenpemberton/status/1505839184... | [deleted] | jiffygist wrote: | Why is css of nitter.net broken? | bryanrasmussen wrote: | Well, my !important story - at the beginning of 2014 I joined a | project that was being done for the Danish government, the | JavaScript implementation of NemID which unless you're in Denmark | you probably don't know what it is. | | Styling in this project was done with a sass compilation to CSS, | and it had hundreds if not thousands of !important declarations | inside it. It seems the guy who was there before me had set up | the import order of the Sass files incorrectly from more specific | to less specific to some really super specific couple things on | top of it all (most of the code base was in Java using GWT to | compile to JavaScript, so as a consequence most of the | programmers were Java guys and did not notice this), basically I | cut 800kb of CSS out of the build in the first few weeks by | restructuring and getting rid of !important declarations (for | anyone who knows NemID you can probably see how this was | definitely way too much CSS for what you need to render!) | | It was my first time consulting, I sometimes thought, man if I | could find the guy who did this (who was I'm told a pretty good | designer) I could just follow him around and make money cleaning | this stuff up! But alas, I ended up having to work for a living. | RandyRanderson wrote: | "co-designer of CSS": right up there with "I invented anti- | personnel mines". | pajko wrote: | After blocking popups on some sites, the scrollbar is dtill | hidden, making it impossible to scroll (like on twitter, for | example). With the help of !important, the scroll bar can be | forcibly turned on by adding uBlock cosmetic filters. Works on | per-site basis, but can be added globally, though some sites | break a bit, like the top header on Wikipedia starts behaving | strangely. | | https://www.reddit.com/r/uBlockOrigin/comments/ce4mok/how_to... | iicc wrote: | If you zap enough elements on Twitter the scroll bars come back | anyway - so !important must be unnecessary for that site. | | https://nitter.net/about offers a better experience IMHO, | because it's fast. | | Is this what the death of the open web feels like? | saghm wrote: | I don't do any frontend development other than sometimes tweaking | custom stylesheets for sites for use with the Stylish extension. | I use `!important` all the time when doing this; a surprising | number of sites I try to modify end up having some stuff with in- | line CSS on HTML attributes, and that's the easiest way to | override it. I don't pretend to think this is an intended use | case of `!important`, but I think being able to customize the way | sites look in ways that I personally prefer is at least in the | spirit of the open web. | taejavu wrote: | If you find yourself reaching for `!important`, try doubling up | the selector instead: | | .someclassname.someclassname { | | That will make it one level more specific than just | .someclassname, which is usually enough to override styles with a | higher specificity, or the same specificity but were loaded | afterwards. If it's still not working, add another one! | | It's a hack for sure, but definitely the lesser evil. | JoelEinbinder wrote: | The most common use for !important is to override something else | marked !important. It's an interesting situation when getting rid | of a feature simultaneously removes most of the need for it. | silvestrov wrote: | It should have been added to the selector instead of the | attribute: div.legaltext:important { font-size: | 12pt; } | | instead of current: div.legaltext { font-size: | 12pt !important; } | | so it would have been a more general "increase selector priority" | syntax, like the opposite of the recent :where(xxx) selector. | zagrebian wrote: | What would :important match? | ailef wrote: | I think in this scenario it is supposed to match all | div.legal elements. The styles are then applied with the | highest priority, thus overriding other rules. | sfblah wrote: | Maybe the html tag could include an important flag | Izkata wrote: | <html id="root"> #root#root#root div.legaltext { | font-size: 12pt; } | | That gives you a specificity that should override | everything else. Would only be a problem if some other rule | has 3 or more IDs, in which case you can add more here. | zagrebian wrote: | Then it's no longer CSS and you have to edit the HTML code | to apply the important styles. | rat9988 wrote: | You already have to if you want your css selector to | select it. | Lapsa wrote: | Recently had to unify looks of pagination rendered by 2 | incompatible approaches. There is a chance it could be done in | more sane ways but I ended up just spamming some very important | css rules and be done with it. | theknocker wrote: | Should have called it "mandatory" then. | ZYinMD wrote: | "!important" means "not important", I guess the engineers didn't | like the law makers so they made this an insider joke. | sequoia wrote: | If this was the intention, it's a bit curious the creators of CSS | waited a quarter century to share this information. I wait with | bated breath for the true purpose of text-decoration to be | revealed. | incrudible wrote: | I would never take advice on CSS by someone who was involved in | designing CSS. | oblio wrote: | The main thing that bugs me about "!important" is... | | Why isn't it "important!" ?!? | | What kind of twisted soul decided to put the exclamation mark at | the beginning? | MartinCron wrote: | I always read it as "NOT important" until I remember that CSS | is its own kind of crazy-town. | lmc wrote: | !Si, que cabron! | rplnt wrote: | Random offtopic rant: | | Twitter had decided some time ago that it would show me one | notification each time I open the website or app. Probably so I | feel like there's something happening. It's always a completely | random tweet from an account I don't follow and it is so annoying | I'm soon going to log out and just live without the few | interactions I do at the site. | lsbehe wrote: | One of the reasons I installed an add-on to redirect twitter | links to https://nitter.net/ | cr__ wrote: | Given that "the cascade" has been a worthless anti-feature since | the beginning, I feel he could have said this in a less | condescending way. | [deleted] | oblib wrote: | To honest, I don't have the time to become a CSS expert so I do | what works and I don't worry much about it. | | I use "!important" quite a bit because I let users made some | choices in the color schemes of the app and using "!important" | makes that easy for me to do. | lmc wrote: | Please, put an id on the HTML element, and a CSS rule targeting | that id, rather than use !important. !important really was a | mistake and should only be used to counteract other uses of | !important you don't have control over. | partiallypro wrote: | The times I use important is generally to override a framework | that is taking precedent, even though the sheet I'm editting is | loaded after the framework css. That is 90% of my useage of | !important. It may not have been intended for this, but a lot of | things in CSS and HTML were never intended for certain use cases | that they are now used for. That doesn't mean it is now misused, | it just means things have evolved. | stefan_ wrote: | Invoking _the cascade_ to explain why there are 15 ways to center | a box, of which 10 don 't work one time or another. | oblio wrote: | I can't find if Tk had this in the original version, but I | suspect that it did. | | For reference, Tk, which was conceptually a decent GUI toolkit | ( https://en.wikipedia.org/wiki/Tk_(software) ), was launched | in 1991. | | CSS was launched in 1996... | akersten wrote: | Anyone have an idea of which part of US Code would require this? | I have a hard time imagining it's that prescriptive about font | sizes (especially given that different fonts have different glyph | sizes, DPI on monitors results in different physical rendering | sizes etc.) Only thing that comes to mind is that Apple court | case many years back where the judge told them they had to have a | disclaimer on their page in a certain size and color as part of | the judgement. | snowwrestler wrote: | Most likely Section 508 of the Rehabilitation Act, which | requires U.S. federal agencies to make electronic documents | accessible. | | The law itself does not prescribe specific font sizes, but | ensuring minimum font sizes is necessary to comply with the | law. | syspec wrote: | Totally agree, if there is such a law - how come now one seems | to have heard of it. CSS was written before ADA, so we can rule | that out. | | Sounds made up | efficax wrote: | oh i understand the cascade, but i also have 25k lines of css to | deal with and deadlines. Yes, I can track down the full cascade | and craft a selector that will specify a rule for just this or | that element, or I can slam a !important on there and move on | with my life | micromacrofoot wrote: | > a sign you may not understand the cascade properly | | What a load of self-important malarkey, this is like telling | someone a hammer should only be used on nails. | | You failed to consider abuse when you designed the spec. That's | not on everyone, that's on you. | [deleted] | null_object wrote: | If this guy was one of the designers of CSS then I have no idea | why he's acting so smug in that twitter thread. | gowld wrote: | If you look at the original CSS spec, you wouldn't be surprised | by smug overconfidence in its designers. | TonyTrapp wrote: | To be fair, I find many of those replies (by other people, that | is) painful to read. Completely missing his point. I'd probably | also get a bit annoyed after the fifth person pointed out | something because they completely misunderstood what I said. | manquer wrote: | I would be annoyed as well, however if I tweet this instead | of say write a well thought out article/blog with some | references then I should expect low quality responses. | LudwigNagasena wrote: | What is his point? It just reads as blame-shifting. | Introduction of an unidiomatic feature into the standard for | a particular use case is an acknowledgment of deficiency or | incompleteness of the whole standard. | tiborsaas wrote: | I think his point is that they added it because they had to | not because they thought it's a good idea. | TonyTrapp wrote: | I read his point being that !important used for anything | but the original intent is "code smell", and I'm fully | behind that. He doesn't imply that you mustn't use it for | anything but its designed purpose, I'm sure he is enough of | an engineer to know that sometimes you cannot stick to your | ideals. He's probably well aware that some people have to | rely on frameworks which already use !important, so they | have to work around that by using !important as well. None | of that contradicts what he says, but it's still a misuse | of the feature. | Dylan16807 wrote: | > I read his point being that !important used for | anything but the original intent is "code smell", and I'm | fully behind that. | | It doesn't explain why using !important for the original | intent isn't equally a "code smell". | | Unless that is smelly too, in which case there are even | more questions to answer about why this is the workaround | and why you're supposed to use it for the original intent | despite that. | thorum wrote: | CSS Cascade Layers are now supported by all major browsers and | provide a good, standard alternative to !important in cases where | you need to override CSS that you can't easily modify, like | stylesheets from a third party CMS or framework, or inherited | spaghetti code from an earlier version: | | https://css-tricks.com/css-cascade-layers/ | wvenable wrote: | It's getting hard to know everything that is in CSS now. | mouzogu wrote: | css "co" designer. that explains a lot. horse by committee. | | i find many uses. sometimes you need to override a style coming | from an external or to apply a rule globally, you can just use | !important and know that it will work regardless of individual | specificity in all instances of that selector. | | yes, you could override it with specificity but why bother, a | hack is a hack | kokanee wrote: | Cascading only works as intended if you don't have third party | styles and if the styling requirements of your application never | change. What's funny is that CSS itself is subject to the same | problems. It was created to help people add emphasis and layout | customizations to text-based technical documents. Now it's used | for everything from interactive maps to control interfaces on | spaceships. | | I get why people hate CSS, but I think the underlying issue is | that it's impossible to create software that can gracefully do | whatever has been asked of it and will be asked of it in the | future. It relates to the whole culture of continuous deployment | and rapid iteration... a few people are talking about the | downsides, but we haven't really reckoned with them as an | industry yet. | jmchuster wrote: | If the requirement was truly only to satisfy ADA laws, then it | seems like you should have implemented it as: | window.ADA_MIN_FONT_SIZE = 16; | | This seems more like you were given the requirement and then | went: | | 1) we could implement this is as a custom global variable for | this specific use case | | 2) maybe what we need is to be able to override a single property | | 3) maybe what we need is to be able to override a group of | properties | | 4) maybe what we need is to be able to define multiple levels of | priority | | and they ended up stopping at (2) when we really needed it to go | to (4) | ivraatiems wrote: | Are you referring to "window" the JavaScript object? If so, | bear in mind that JavaScript is not a requirement for CSS to | work on a page, and CSS creating a dependency on JS would break | a _lot_ of things. | jmchuster wrote: | Sure, then make it a meta attribute. Just needs to be a | global somewhere. | francisofascii wrote: | Especially back when CSS was created, disabling JavaScript | was much more prevalent. | lmc wrote: | > important was added for one reason only: laws in the US that | require certain text to be in a given font-size. !important stops | the cascade from changing it. | | But it doesn't. !important begets more !importants. | | Nice to hear the reasoning behind it, but it's a PITA and should | never have been added. | jansc wrote: | I always thought of important as the sudo of styling. | AtNightWeCode wrote: | Not really. | LudwigNagasena wrote: | I don't understand the sentiment. If there is a functional | requirement that can only be reliably achieved with that hack, | doesn't it suggest that there are other possible functional | requirements that can only be reliably achieved with that hack? | __del__ wrote: | yes. the moralistic sentiment seems to be that you should only | resort to the hack when faced with legal consequences. | [deleted] | paulodeon wrote: | This confirms my suspicion that CSS was designed in an ivory | tower. | | Despite being a "good developer" cut my teeth in C++ etc always | had difficulties with CSS. The mental hurdles required to | understand various concepts bore no relation to anything else I | had encountered in CS. | | I'm sure a notable percentage of my grey hairs are attributable | directly to its incredible user-unfriendliness. | postalrat wrote: | I find the hardest thing with css is getting it right the first | time. If I'm on a project and I can care about css I find I'll | end up refactoring classes a couple time before I'm happy. | datavirtue wrote: | Exactly. CSS is doing too much. All the decisions seemed to | make sense at the time but it all ends up being a clusterfuck. | Part of it has to do with everyone having to rebuild HTML/CSS | parsers from scratch and the ever changing and evolving nature | of the markup. | | Just when you think everything is going to be OK you are faced | with feeding your document into another parser that isn't at | parity with the browsers. A lot of people struggle to build | PDFs from HTML where the parser (itext) only understands a | certain subset. That nice grid layout you designed? ...throw | that out. You need page breaks with common headers and footers? | Get ready to commit some really dirty hacks. Should this data | be in a div table or a semantic table? Better predict the | future. | alerighi wrote: | Why do you need to rebuild parsers from scratch? You can just | use Chromium. Want to build a PDF form an HTML page? You can | launch chromium in headless mode and tell it to print your | HTML. Guaranteed that you will have a good result. I don't | understand where you have this problem these days. | | Also, nobody really asks you to do complex things with CSS. | Unless you use a huge framework (that I tend to avoid, I | prefer writing everything from scratch) you don't need too | much rules to make a page look good. In 200 lines of CSS you | can get a good style for your site. | | The problem is that people: | | - think that frontend development is easy and have less | dignity than other kind of software development - don't want | to spend time learning CSS since it should be simple - don't | know CSS and don't understand it - use a framework like | Bootstrap because they don't want to learn CSS - complain | that CSS is shit because they have to use a ton of !important | to make things work | | CSS is easy if you dedicate enough time to learn the basics | of it, and start to make some stylesheets from scratch | without Bootstrap or other shit. | 7sidedmarble wrote: | I've also lost count of the number of systems/backend guys on | this website who hate the frontend world even though they've... | Never really done it professionally. | | I think because frontend has a reputation for being easier, | there's this assumption that if you can do the 'harder' thing, | you should be able to pick up JS and CSS pretty easily. | | But the truth is, what separates a great frontend engineer from | an ok one is mostly knowledge of the history and the ecosystem. | The web is a big stack of compromises. Knowing why things are | the way they are is one of the only ways to make sense of the | frontend. That and just actually doing it. | epolanski wrote: | > what separates a great frontend engineer from an ok one is | mostly knowledge of the history and the ecosystem | | And here I thought it was related to getting the best result | (most value for the user/customer) in a set of constraints | such as requirements, team and time... | replygirl wrote: | it's not programming, it's markup for a renderer. it's just a | different skillset--people who fiddle with shaders in a blender | GUI are better prepared to work with CSS than most programmers. | i was great at css when i was 12 but wasn't a half-decent | programmer until i was 25 | notacoward wrote: | Having to comply with a legal requirement is very real world. | Practically the opposite of the ivory tower. | robbrown451 wrote: | I don't think that's the part that is "ivory tower." It's the | attitude of "you should never use this feature that you rely | on unless you are doing one very specific thing that | necessitates it" as opposed to just saying "let's design it | in a way that such things can be done easily and without | violating the spirit of the language." | JoeyBananas wrote: | I've used !important plenty of times when I had no idea what it | actually does just because some random tutorial suggested it | saos wrote: | HTML email enters chat | zagrebian wrote: | [hidden] { display: none !important } | MonaroVXR wrote: | One the best CSS tricks out here, thank you. | heavenlyblue wrote: | This css nazi could also check out the CSS scoring system for | different types of elements (id/class/tag name) which completely | goes against specificity/hierarchy/ordering of the rules. | | !important really helped fixing the CSS in the cases where | engines used those element references super liberally and thus | you needed to clearly set an override without refactoring the | whole CSS rule set. | soheil wrote: | What? no, you can override !important many ways, for example # | rules take precedence over . rules, so even if you have important | in your . it could get overridden. If you obviously add inline | style that will also override it, etc. | lnxg33k1 wrote: | I have the feeling that a lot of these people who are very smart | and design things sometimes live outside of the world and don't | know mere mortals issues, I might be understanding cascading and | important (I don't like to use it either and avoid it), but we | need to make sure that we know that we work with some legacy | code, as part of a team, some decisions made before us, tight | deadlines and pushy managers, I won't use !important, I might | understand cascade, but I also don't want to refactor everything | everytime I can't use a shortcut, when its simple changes it's | fine, when it's not maybe !important + a ticket to refactor in an | allocated time is a better approach | trinovantes wrote: | One nice feature modern frontend frameworks have nowadays is | automatic component specific css rules | | IIRC in Vue, <style scoped> allows each element of the component | to have an data-{id} attribute and every CSS rule is appended | with [data={id}] selector so you're guaranteed no CSS rule leaks | out and is contained in the same file | [deleted] | dpcan wrote: | Seriously tho, it comes down to dollars and cents and the fact | that !important is an option (and not just for font-size). | | A client says they'll pay for 30 minutes, the boss won't let you | go over 15, it's not like there's enough time to actually wiggle | your way through a CRM to drop the proper CSS, so a little | !important in the override inline CSS is what happens time and | time again. | | Good developers would love to take the time to do things right, | but we don't always have control over these situations and it | stinks. | omnicognate wrote: | The only reason !important was added was to troll javascript | programmers, who read it as "not important". | pistoriusp wrote: | isn't ! a fairly common negating symbol in programming | languages? | omnicognate wrote: | Yes, it's by far the most common use of "!" in programming | (though newer languages are increasingly using it for various | flavours of null/nothing checking too). Javascript just seems | particularly relevant here. | LeifCarrotson wrote: | C programmers, and those who write in languages derrived | from/inspired by C. | adzm wrote: | Should have been !!important instead. | nick__m wrote: | IMHO, there is another valid usage: client side css, when a rule | is as specific as it can be the !important attribute might be the | only way to locally override it. | [deleted] | jstummbillig wrote: | That's fine. It's really not that important what a designer of | CSS thinks about how any part of CSS is being used. A guitar | player does not confer with the guitar builder about how to play | the guitar. | pdimitar wrote: | Damn, there are still people believing that you can just express | what the intent behind an engineering tool was, and people will | only ever use it if it matches that intent? | | That would be crazy naive and I hope this person doesn't imply | that. | | Everybody is on a schedule. People reach for whatever is | available. Doesn't matter what was the reason `!important` was | added, at all. If it solves a real problem -- especially quickly | -- then people will use and abuse it. | iambateman wrote: | "Anything else is probably misuse" is simultaneously true and | brushes away all the realities of front end development. | rectang wrote: | It requires discipline beyond the capabilities of many | organizations to structure CSS so that it's maintainable. The | ubiquity of `!important` is not so much "a sign you may not | understand the cascade properly" as a sign that the cascade is | a flawed design that falls apart in practice. | nawgz wrote: | Step 1: Write component-based UIs Step 2: Give each component | a unique name Step 3: Repeat this principle even for building | routes Step 4: your CSS will struggle to clash, no matter how | hard you try | | The cascading is pretty nice actually. Think about using CSS | vars... you can dynamically theme apps because of the | cascade, by changing just 1 class. there's other nice | attributes, and it's true it requires discipline. Just not | nearly as much as you imply | shadowgovt wrote: | Step 2 demands there be a way for one developer to control | the global namespace. | | That's completely impractical[0] given inclusion of 3rd- | party code and no enforceable standard for imposing step 2 | on other developers. | | (Web components now exist to facilitate this, but of | course, web components are relatively recent; most of CSS's | history did not support this 4-step process). | | [0] To be fair, maybe _completely_ is too strong an | assertion. I 've seen something like it done... A compiler | rewrites the CSS selectors and the CSS classes to create a | sort of top-level namespace by prepending some garbage per | module so that no component can accidentally reference | another component. It's not great for debuggability (about | as much fun as having to deal with the actual entrypoint | names in the binary for constructors and overloads when | debugging C++), but it gets the job done. | nawgz wrote: | > Step 2 demands there be a way for one developer to | control the global namespace | | I mean, I just prepend all my component class names with | my library name or a shorthand acronym, so 100% of my | styles are like `.NawgzInput {}` or `.NawgzGraphNode {}` | | I have never seen the limitation to this approach (i.e. | the ends of its ability to scale), so long as you don't | pick a super generic prefix. So to hear you assert this | approach is "completely impractical" to someone who has | used it to build their own component library that every | application they build is entirely comprised of.. rings | hollow | shadowgovt wrote: | You're basically hand-rolling the prefix-garbage solution | the compiler tool I've seen does. | | That's the best I think we have now. It's not good (i.e. | decreases readability), and it's not universal (there are | definitely component frameworks out there where the | classes are just named "table" and "button"). | nawgz wrote: | > You're basically hand-rolling the prefix-garbage | solution the compiler tool I've seen does. | | Except it's incredibly easy to debug and avoids most of | your complaints about the solution. | | Anyways, fair enough, I can confess that there is | probably another ideal world that has better viewport | styling. But CSS is giving us incredible flexibility, and | just like JS, its warts can be worked around very easily | and deliver you a powerful, useful, simple set of | capabilities. | Pxtl wrote: | If component-based UIs are such a good idea, maybe the w3c | shouldn't have designed literally every piece of the | HTML/CSS/JS infrastructure around global namespaces, | particularly ones where every declaration is global _by | default_ in the case of CSS and HTML IDs. | | "Global all the things" seems to clash with "component". | rectang wrote: | When hunting down a function you want to deprecate/remove | in your private imperative language codebase, you can | probably find all call sites just by grepping -- and even | if you miss some, in most cases you'll get a hard error of | some kind (either compile time or runtime) after removal. | | But with the cascade, call sites are implicit -- and | removal, for better and worse, doesn't cause a hard error. | | All it takes is a single rogue engineer or product manager | to mess things up. And then cleaning things up later is | difficult because of all the places that have to be | inspected. | BitwiseFool wrote: | Very few clients care about how "proper" the CSS is behind the | scenes. I'd also venture that they would not want to pay for | proper CSS (and the expense of expertise that comes with it) | when a single attribute would deliver the same end result. | !important actually seems like a practical and valuable | attribute in this regard. | datavirtue wrote: | It comes in real handy when the css hits about 300k lines. | True story. | [deleted] | Minor49er wrote: | A lot of people have been pointing this out in the responses. | The author has been defending himself for people misreading his | tweet when he should have simply left out that last sentence | human wrote: | Sometimes a tool has been invented to do X but people end up | using it for Y because it's so useful. I think "!important" is a | good example. Like duct tape being used for much more than | attaching ducts. | tfvlrue wrote: | The ironic thing here is that traditional duct tape should | _not_ be used for attaching HVAC ducts together. The adhesive | doesn't withstand the temperature extremes, and it has | undesirable properties if it catches on fire. UL-listed foil | tapes are used for this instead. | | It seems like cloth-backed tape started as "duck" tape (as in | duck cloth), somehow turned into "duct" tape, and then turned | back to "duck" for marketing purposes. It has quite an odd | history. | 10000truths wrote: | I remember having to use !important statements to override | styling when making custom CSS themes for subreddits, back when | old Reddit wasn't old. | nathias wrote: | it's very useful when you are hacking on top of existing code | that you don't have access to, like custom skins ux for websites | you use | hutrdvnj wrote: | What happens in case of multiple contradicting !important | statements? | cxcorp wrote: | CSS has a concept of "specificity" [1] which is applied also in | the case of !important. Basically the most specific rule wins. | | [1]: https://developer.mozilla.org/en- | US/docs/Web/CSS/Specificity | maxbaines wrote: | In-line css takes priority. | zigzag312 wrote: | If a simple condition like this requires some special solution, | isn't that a sign that there are probably some a fundamental | issues with your system? | bdlowery wrote: | The same thing can be said for a lot of things with CSS... | | The @media rule was added for one reason only: provide different | styles for different media types. It wasn't intended to be used | to make responsive websites. Is using it to make responsive | websites an incorrect usage? | [deleted] | dvt wrote: | Bragging about "designing CSS" is a bit like bragging you | captained the Titanic. I mean, I guess it's impressive, sure, but | it's also pretty embarrassing. I've used `!important` many times, | as I'm sure many folks did, because CSS just absolutely sucks and | it's a huge pain the butt to get it to do what you want. Using | `!important` is the equivalent of throwing your hands up in the | air and saying "screw it, I wanted to go home 3 hours ago, I'm | done." | | On a side note, CSS3 being accidentally Turing complete is | probably one of the funniest (read: dumbest) things out there. | vlunkr wrote: | I don't read the tweet as bragging | savanaly wrote: | Engineering is doing what you can with what you've actually got. | If what you've actually got is an inherited tremendous ball of | spaghetti css, a need to change just one thing on the page, and | scant prospects for future changes in the area, then it may be | good engineering to use "!important" to make your change over a | more complex solution. This is in fact the situation I find | myself in at work somewhat often, although luckily I can't recall | the last time I had to use "!important". But I wouldn't issue a | blanket disendorsement of it. | dheera wrote: | I use !important all the time to get rid of fucking GDPR popups | and things like that. | dorgo wrote: | What do you do if you encounter GDPR popups with !important | directive? I think we need !!important... | dheera wrote: | I think if your CSS comes after theirs in the DOM yours | will take priority. | innocentoldguy wrote: | While I agree with your statement overall, most of the time, | using !important just kicks the problematic spaghetti-code can | down the road. The CSS eventually becomes un- | workable/maintainable. | | At one place I worked (a subsidiary of NTT), the effort to | clean up the CSS and remove all the !important overrides was so | time consuming management wanted to make sure it never happened | again, so using !important at all would affect our performance | reviews. We were expected to fix any bad CSS right away without | overriding the default cascading rules. | rossdavidh wrote: | "The CSS eventually becomes un-workable/maintainable..." | | True that, but sometimes one has already reached that point, | and yet must make this change anyway somehow. But I don't | recall using "important" in years, so I guess it's not that | often. | DonHopkins wrote: | Speaking of working with what you've actually got, CSS source | code so looks dull and boring, all in the same font and style | and format. | | I want to be able to mark up my CSS sources with HTML tags, and | style it with CSS, so it's beautiful self documenting literate | code! | | Imagine how easy and pleasurable to read and understand CSS | would be you could simply use CSS in your CSS to format "font- | weight: bold" in bold, and "font-style: italic" in italic! | 3np wrote: | Xzibit Style; Pimp my sheetz | galaxyLogic wrote: | Right, the flaw in this argument: > Anything else is probably | misuse, and a sign you may not understand the cascade properly. | | is that it assumes the cost of changing the "whole cascade" is | minimal. And that it would be easy to design an initial cascade | which works perfectly for your needs without any changes needed | as the design evolves. In other words it assumes the classical | waterfall method where the spec and design are complete and | never-changing once the "implementation" phase begins. | | The suggestion is that there is nothing wrong with CSS, only in | developers who can not come up with a perfect CSS-design before | they start coding. | | A big problem with CSS in my view is precisely its cascading | nature. When you change anything anywhere it can break things | in many other places, and there is no good tool as far as I | know that would tell you what all can change because of any | given change in a single CSS-rule. It is assumed that | developers should have such a tool in their brain, and if you | don't you are not a worthy developer. :-) | willseth wrote: | Having a good justification for misuse doesn't make it not | misuse. And bad tooling and hard-to-understand CSS design | might be reasonable excuses to not understand cascades, but | the point is valid -- even more valid. | MatthiasPortzel wrote: | One place where I end up using !important very frequently is | writing user-styles/extensions for websites. Obviously not a | common use case, but it makes me glad that CSS has | `!important`. | | If you're explicitly trying to overwrite another rule _that you | do not control_ , `!important` is more idiomatic than the | alternative. (If you've lucky enough to have never had to do | this, the alternative is adding otherwise pointless qualifiers | to your selector, since CSS gives higher priority to "more | specific" selectors. e.g `html > body > div {...}` takes | precedence over `div {}`) | mattwad wrote: | One caveat: every time I use !important, there's at least a | clear reason why ("X" library is doing stupid stuff) and you | could be surfacing this like any other tech debt. Often, | 'spaghetti css' is an easy excuse to not even look into what's | going on. | cpfohl wrote: | Yup. If you've used important it should be accompanied by | documentation. So much of frontend development work is using, | adapting, updating, or integrating code you have no control | over that it's inevitable to need to use some blunt force on | occasion... | blowski wrote: | Technical debt in CSS seems to be both more inevitable and less | problematic than application code. By the time it becomes a | problem, either marketing decides on a redesign or the latest | frontend lead wants to use a new framework. | | So "screw it, this works" seems to be an entirely justifiable | methodology. | meerita wrote: | OOCSS leads you to technical debt. The bigger you become, the | easy you land into techdebt. | orwin wrote: | OO leads to technical debt in most cases. You can limit it | to a narrow scope (interfaces), or you can have objects | that wont move or inherit much (bascially if the parents | can be replaced by traits), but someday someone will try to | be clever and your team will soon enter OO hell. Bonus hell | points if you allow third-party plugin in your software | (shoutout to Jenkins!). | hinkley wrote: | > So "screw it, this works" seems to be an entirely | justifiable methodology. | | I've become more aware over the years that some developers, | especially very senior ones, are under the fatally mistaken | assumption that the problems start when the complaining | starts, when it's closer to the truth to say that the real | problems start when the complaining ends. | | There can be bad developers on any team of course, but there | are many developers who know or suspect what they are | considering doing is wrong, and discover that asking someone | about it is far more trouble than its worth. They either get | yelled at or saddled with a bunch of homework because they've | drawn attention to a can of worms and are being deputized to | fix four things instead of the one they knew about. | | Every project has problems. Even the ones that are making | millionaires out of relatively new team members. If you | aren't hearing about those problems, that's entirely, 100% | your fault. | y4mi wrote: | Not all problems have to be solved before they become an | issue though. | | Its often a pointless effort, especially if the problem | boils down to "this architecture isn't pure enough" | epolanski wrote: | > real problems start when the complaining ends | | I really like this quote, and I'm gonna reuse it in a | slightly rewritten fashion. In SE teams, indeed, the amount | of complacency is directly related to the amount of | increasing technical debt. | daveslash wrote: | In my career, I've gone from Waterfall, to XP, to Agile/Scrum | methodologies.I've also spent some time doing V-Model. | Personally, I'm looking forward to the switch to the _" Screw | It, This Works"_(tm) methodology. Looking forward to the | Addison-Wesley book series! | | Edit: I've just founded the _" Screw It, This Works"_(tm) | Alliance. Sign up today to become a certified _SITW_ Master. | dorgo wrote: | It's way better than "Screw it, it probably doesn't work, | but we have new projects to work on." | [deleted] | eqmvii wrote: | we call that "fuck it, ship it" | FerociousTimes wrote: | or exceptionally better "Fuck it, we'll do it live" | sokoloff wrote: | "Let's get this working in prod; after that, we'll back | patch it to dev..." | eurasiantiger wrote: | Brand it FISIcal Project Management. | winged wrote: | Deadline Oriented Programming. | vlunkr wrote: | > Technical debt in CSS seems to be both more inevitable and | less problematic than application code | | Nicely put. I've stressed over finding unused rules, | restructuring, etc. but in the end it never matters as long | as it displays correctly. | rectang wrote: | The big problem is knowing all the places which could be | displaying incorrectly when you make a change. This is a | fundamental design issue with the cascade: unbounded silent | failure because rule activation is implicit. | | In addition, there is the difficulty of inspecting those | sites which you _can_ identify to verify that display is | correct, which is hard to achieve programmatically. | inopinatus wrote: | That's fine for your brochureware whatever. Not fine for a | line-of-business application meant to be useful for the next | decade or more. | xiphias2 wrote: | It's not inevitable. I love Svelte partly because it solves | the problem by compartmentalizing CSS to the UI component I'm | working on. It feels natural that if I write CSS in a file | for a component it shouldn't be seen by other components in | general. | ravenstine wrote: | Even without Svelte, most of the problems people have with | CSS go away if you do the following: | | - Avoid cascading (i.e. no nested selectors except when | there's "no other way") | | - Implement separate selectors for styling and | page/component layout (separation of concerns) | | - Using a good naming convention and stick with it | | The first point can also be achieved with using style | attributes if that floats your boat, although Svelte kind | of gives you the best of both worlds just by | compartmentalizing the CSS, not necessarily by preventing | cascading. | | I can't remember the last time I ever had to use !important | except when I had to work with some ridiculous CSS | "framework" my predecessors chose to use. At least | !important was understandable back in the days when it was | really hard to achieve some things with CSS, but these days | I believe there's little to no excuse. | reactor wrote: | Mind telling a bit more on this second part "Implement | separate selectors for styling and page/component layout | (separation of concerns)"? Are you referring to classes | (for styles) and probably id's for Javascript? | xiphias2 wrote: | I believe that Svelte is so natural extension to the | current web that - just like with CoffeeScript and ES6 - | some of it should be adopted. | | Importing HTML files as modules with localized CSS+JS as | web components would be one such option for example. | replygirl wrote: | this is called an html module: | https://github.com/WICG/webcomponents/blob/gh- | pages/proposal... | xiphias2 wrote: | Thanks, it looks great. I'm happy that they didn't rush | it. They don't talk much about compatibility with current | web frameworks, I think they should. I really hope that | it will be featureful enough to support being a target | for compiling Svelte components (or even maybe React / | Vue components) to HTML modules to be imported at some | point, but still stay simple enough to be useful. | [deleted] | bobbylarrybobby wrote: | Points 1 and 2 sound a bit like CSS's new "layer" feature | alskdjflaskjdhf wrote: | On the other hand, I find Svelte's handling of this half- | baked, as there's no way to pass scoped classes to a | component, only to a HTML element. [1] In fact, I find this | so frustrating that I have actually given up on Svelte's | CSS scoping entirely and I use Tailwind instead, which also | solves the same problem by almost [2] completely | disregarding the cascade altogether. | | [1] Why would you want to do this? Well, what about layout? | And what if you have a component that wraps or otherwise | behaves like an HTML element? | | [2] Of course Tailwind supports modifiers, which do | cascade, but everything is still local to a single element. | xiphias2 wrote: | One of the questions for passing scoped classes to a | component is why you want to do it. If you have complex | selectors, it would effect the implementation of the | component, so I think that would be an anti-pattern. Just | modifying the root would be great, but in Svelte I | believe one component can translate to multiple root | nodes, so all of them would need to get the styles, which | again would increase the coupling between the component | usage and implementation. I think there's just no clean | way to do what you want. | alskdjflaskjdhf wrote: | I already said why in my first comment: | | > Why would you want to do this? Well, what about layout? | And what if you have a component that wraps or otherwise | behaves like an HTML element? | | Yes, it's nothing something you'd want to do willy-nilly | or all the time, but there are perfectly valid use cases. | This issue has been one of the single most-commented in | the Svelte repos with tons of back and forth and a lot of | demand so this isn't just an obscure complaint either. | | As for how to resolve it, there are plenty of clean ways | to do it. Svelte's style scoping is done via a unique | class per component. It suffices to simply provide some | way to pass this class from a parent to a child, for | example, and let the child component decide what to do | with it. There are many possible variations on this | theme. The obstacle to resolving this problem isn't | technical infeasibility, it's that to date the | maintainers just haven't cared. | madeofpalk wrote: | This is why, as someone who loves writing CSS and thinks | they're reasonably good at it, I've come to the conclusion | that writing CSS is an anti pattern, and if you want teams to | quickly build interfaces with a maintainable "frontend | styling layer", it should prevent the ability to write css. | felipemnoa wrote: | What would you recommend instead of CSS? | xeromal wrote: | tables | bamboozled wrote: | Tailwind | eurasiantiger wrote: | ... which is a CSS utility class library and thus suffers | from some of the same pitfalls. | | How about something like Ant Design? | svachalek wrote: | Unless something major has happened to it since I used | it, Ant uses a giant ball of SCSS with complex selectors | that make it ridiculously hard to customize without | hacking the source. | eurasiantiger wrote: | Hacking is exactly what we are trying to avoid. Just | change the variables to suit your branding and compile | the SCSS yourself, just like Bootstrap (which was using | LESS but otherwise the same idea). | SheinhardtWigCo wrote: | I think utility-first frameworks like Tailwind are becoming | popular because they allow frontend teams to say "screw it" | without descending into total anarchy. | soperj wrote: | You should probably use specificity first, then important, just | in case you need to over-ride it in the future. | have_faith wrote: | Being more specific often ends up more tightly coupling your | selector to the structure of the DOM. .className { property: | value !important; } is more resilient to DOM changes than | adding extra selectors to increase specificity. | soperj wrote: | I haven't found that to be the case. | csnover wrote: | I've noticed many CSS authors don't seem to know that you | can just repeat a selector to increase its specificity. For | your example, `.className.className` increases the | specificity without adding more reliance on DOM structure. | dopamean wrote: | This is a really cool tip. | 3np wrote: | You can also do !important !important. | jimhi wrote: | I did not know this, thanks for the tip | jaywalk wrote: | Wow, I've been doing CSS for a very long time, and had no | idea about repeating the selector to increase | specificity. That'll come in very handy, thank you! | smegsicle wrote: | having an id on the top <html> tag and mentioning it in css | rules seemed very effective to me- especially when the tag | was the name of the page, which is what i wanted to | override by anyway | debesyla wrote: | I personally like the body:not(#fakeid) trick :-) | datavirtue wrote: | You know what I hate about CSS? Having to learn a bunch | of "tricks." | hallway_monitor wrote: | So much so that a business with those keywords recently | sold for eight figures! | calibas wrote: | This, if you understand the CSS rules for specificity, you | almost never need to use !important. | thrwy_ywrht wrote: | On the other hand, using ever-increasing specificity to | emulate !important is about as elegant and semantic as | using the hypothetical properties !importanter, | !importanterer and !importantererer | calibas wrote: | Ever-increasing specificity is how CSS works, to call | that "emulating !important" is misleading. I'm suggesting | using CSS as intended, the cascading part of cascading | style sheets, instead of relying on a troublesome | override. | | _Edit:_ Take this example: div {font- | size: 60% !important;} | | If I can't control the order the CSS is loaded, and I | can't change that line directly, how do I modify it? Like | this: html div {font-size: 70% | !important;} | | The use of !important isn't some simple way of bypassing | ever-increasing specificity. In many cases it just makes | things more complex. | cerved wrote: | That's a quick fix and I fail to see anything engineering | specific about it. The same approach can be applied to any | other problem in any other profession. Personally, I'm not a | fan of this approach. | | I also think it's the wrong quick fix. What you want is a rule | of increased specificity. Better use a unique id, maybe in | conjunction with an element selector. | | !important rules should be avoided like the plague | edgyquant wrote: | This can be a slippery slope. I've seen projects with an | initial nice hierarchy become spaghetti when engineers looking | to save time start throwing important everywhere. | | Not that it should never be used. It's like gotos in C code. | They definitely have a purpose but if you find you've | implemented more than half of your program control via gotos | you've probably made your codebase into a horrific mess. | nojs wrote: | I think it's fair to say at this point that the "semantic classes | with reusable cascading CSS" experiment has lost to local, | component-based solutions. Overuse of !important is just another | sign of that. | | Having "clean" CSS doesn't have the same benefits as clean, well | structured code in other areas. The underlying assumption that | you can change the visuals without major surgery to the HTML is | basically never true, so if you do put the time in to structure | the CSS perfectly it's often wasted when the design changes a | little. | | Also (as someone said in another comment) the lifetime of CSS is | short compared to other application code and certainly compared | to backend data structures and business logic, meaning the | technical debt isn't a huge issue. Iteration speed is often more | important. | replygirl wrote: | "'gif' is pronounced ____" energy | politelemon wrote: | What's the source for this, I do see they're the CSS co-designer, | was this requirement originally written somewhere? I'm looking at | the description of important, and I don't see this intention | carried through. | | https://www.w3.org/TR/css-cascade-5/#important | | https://www.w3.org/TR/css-cascade-5/#importance | | If the intention is indeed as described, then the CSS designers | failed to communicate it properly, and not "a sign you may not | understand the cascade properly." | simonlc wrote: | I don't know of it's a joke tweet, or a pompous person trying | to make other devs feel inferior. | | The example or use case they describe doesn't even make sense | to me. Nor does it even seem to line up with how CSS | specificity or cascade works. | | "Here's a paper to write on, oh wait why are you drawing, this | is a writing paper, you're doing it wrong!" | throwawaylala1 wrote: | > or a pompous person trying to make other devs feel inferior | | This is how I felt reading it as well. IMO Steven should | exercise a little humility. | | It was bad design on his team's part. How is anyone supposed | to know that there was only one super secret reason for | "!important" to exist? Why not call it something like | "!break-cascade-override"? They put an emphasize on making | the language look "clean" over real world usability and this | is the outcome. | makeworld wrote: | >> Are there public discussion records about this? That'd be | entertaining to read | | > Alas not. I wish there had been an agreement that after some | number of years the records would be made public. | | https://twitter.com/stevenpemberton/status/15059585359763456... | hacktavist24 wrote: | When you say "If the intention is indeed as described," are you | referring to the tweet in the submission? Because it looks like | the intention is indeed so described in the links you give: | | > This CSS feature improves accessibility of documents by | giving users with special requirements (large fonts, color | combinations, etc.) control over presentation. | Vinnl wrote: | Yeah, I seem to recall it was added in Firefox to solve some | browser chrome styling issues, or something like that. Anyone | any idea where I got that idea from? | sfblah wrote: | If the intention had been to comply with laws, why use | "!important" as the keyword? | akersten wrote: | For the same reason we call it "accessible entrance" and not | "government-mandated alternative door with ramp." Making the | phrase more general is just good design. | bigyikes wrote: | But nobody is saying that accessible entrances should only | be used for disabled persons and nothing else. | | Here, the author is asserting that there is only one valid | use case of !important, and that it shouldn't be used in | the general case. If it shouldn't be used generally, having | a general name is bad design. | jraph wrote: | It should have been "!legally-required", or "lawful-font- | size:" | | or the React way, "!enforce--only-use-this-for-legal- | font-size-or-you-will-be-fired" | throw0101a wrote: | Can anyone give an ELI5 to us curious non-webdevs about why | !important seems to be A Thing? (As a sysadmin I'll probably | never have a practical need for this, but it's always fun | learning about the various niches in 'tech'.) | cxcorp wrote: | CSS stands for Cascading Style Sheets. The _cascading_ part | refers to the fact that when you have a HTML element which is | targeted by multiple style rules (e.g. browser defaults, style | sheets, inline `style= ""` attributes, inherited from a parent | element's rules, etc.), there's a well defined priority order | which decides which style "wins" and is in effect. | | For example, you might define that all body text is black, but | then also have a rule that says that if it's a link (an `<a>` | element), it's blue. Suppose you want other links to be blue, | but the links in your navigation bar should also be black. Can | do, just specify `nav a { color: black }` - now rest of the | links are blue, except inside your navbar. | | This is neat, because with relatively concise notation, you can | specify styles for the majority of your site, but can also | easily specialize styles when you need to. Compare that to | manually setting `style=""` attributes on every single HTML | element! | | So what's the problem with !important then? !important is #1 in | the priority order I mentioned previously, so when you add | !important to a CSS declaration, you throw out the first C from | CSS. You're saying "I don't care what any other stylesheet or | style rule says - ignore them and use this rule". To beat | !important, you need to also add !important, and additionally | make your CSS rule more "specific" than the other, e.g. `nav a | { color: black }` beats `a { color: black }` because it's more | _specific_ - "target <a> inside a <nav>". | | This becomes very problematic if e.g. a third party component | uses !important in its rules. Let's say that third party | component's stylesheet overrides all <a> elements to be red. | Great! Every single link is now red - including the ones in | your navbar. You'll now need to go back to your own rules and | add !important there - meaning now you need to use !important | in every single declaration to get the C back into CSS. | throw0101a wrote: | > _!important is #1 in the priority order I mentioned | previously, so when you add !important to a CSS declaration, | you throw out the first C from CSS._ | | So the exclamation mark basically takes on its 'linguistic | meaning' that this particular definition should be given | extra emphasis. | | I was interpreting the "!" in this conversation as it is | often used in tech, as a "not-" prefix. :) | | Thanks. | adzm wrote: | Should have been !!important instead. | oblio wrote: | Or, in the spirit of Javascript == / ===, !!! | jvalencia wrote: | A sysadmin analog: When you have $PATH defined globally, but | you want to overwrite it for a specific command: | | >> PATH=/special myscript.sh | randomdata wrote: | Apparently to force font-size directives when legal | requirements are present. | kradeelav wrote: | Not a webdev by profession, but hand-coded a few hobby sites - | !important is used as a duct-tape "just do the dang thing" hack | if you need to overrule a bunch of the current styling rules | and don't want to think too hard about it. | s-xyz wrote: | Oh my, I used to have stylesheets with more than 500 line, where | every single line ended with !important; | [deleted] | beardyw wrote: | How can a font size be subject to legislation in anything CSS | controls? It won't absolutely define the size on screen or on | print, will it? | lopis wrote: | The important statement is also useful is you're creating | something to slap on some other code you have no control over. | Examples of this from my experience are: | | - debug tools that hijack the pages style - quickly testing | styles on the browser while coding - widgets that are injected | into client's websites; client's websites can be a mess, and | might contain important statements themselves... - browser themes | or custom styles | | Sometimes it really doesn't matter that! Important is bad | practice, if the alternative would be 5x more verbose and | confusing. And honestly I don't care what the father of CSS | thinks. | edgyquant wrote: | It works nicely if you are debugging CSS via the inspector. But | if you start slapping important all over the place you | eventually converge towards a code base where a majority (or | large number) of classes are using important which takes you | back to square one. | Fnoord wrote: | > Anything else is probably misuse, and a sign you may not | understand the cascade properly. | | I use it in userChrome.css in Firefox to hide tabs because I use | vertical tabs. I copied that snippet from some FAQ and it Just | Works (tm). ___________________________________________________________________ (page generated 2022-03-21 23:00 UTC)