From the course: CSS for Developers

Declarative vs. imperative languages - CSS Tutorial

From the course: CSS for Developers

Declarative vs. imperative languages

- [Instructor] CSS is a declarative coding language. Understanding the difference between a declarative language and an imperative one is important to understanding the nature of CSS. Most programming languages are imperative. They provide detailed step-by-step instructions to the computer about how to perform a sequence of actions. Do this, then do this, then do this other thing exactly as I said. Imperative languages give you full control and an opportunity to mess up. The computer will do exactly what you tell it to do. And if your instructions lead to errors, well, then those errors happen. Declarative languages like HTML and CSS are different and forgiving. Instead of telling the computer exactly what we want it to do, complete with step-by-step instructions, we give the computer a description about what we want, generally describing an end outcome, and the computer decides how to make that happen. So for example, using CSS, you could say, take this container, make it 50% of the viewport width, and make the background color purple. And then we leave it up to the browser to figure out what 50% of the viewport width means in the current context. Maybe that context is a phone screen or maybe it's a large display. The browser then has to figure out how to apply the background color and any other styles that we've defined for that container. The key here is that the browser decides how best to achieve the goals set out in our instructions, and consequently, how best to deal with errors. It's helpful to think of imperative coding languages as active commands, and declarative languages as passive requests. In an imperative language such as JavaScript or PHP, we give the browser commands on exactly what to do. In CSS, a declarative language, we give the browser a request for how we want a selected element to be rendered. This is something important to understand. Because CSS is declarative, even if the browser can't or won't follow our instructions, no error is triggered. Instead, the instructions are just not followed and we get some sort of default output. This fault tolerance is what makes declarative languages like HTML and CSS incredibly powerful. CSS errors don't destroy the site, but it can be frustrating if you're working in imperative languages, because you're not getting explicit errors, and you're sort of at the browser's mercy to do what you ask it to do. If you get frustrated, remember this, the declarative nature of HTML and CSS is a specific design choice for the web. It ensures that the web is robust, making web content accessible, even when there are errors in the code.

Contents