top of page
Search

How does CSS work?

With all the fancy tools in the palm of our hands it can be a little confusing as to how CSS actually works.

Gone are the days of manual labour, with a few clicks of a button in your prototyping software you can export out the necessary CSS to put together in your code blocks.


But even in an auto generated world which we live it is still paramount to understand how something like CSS works.


How do you know if you are auto generating too much CSS? Or whether there are duplicates in your code?


The software principal called DRY — Don’t repeat yourself.


Sometimes duplication can be on the plus side as you want to quickly prototype something up without converting it into a UI Block or Component and other times, duplication creates more errors especially if it passes into the hands of the engineers.


How does CSS work?


I often think of CSS as a waterfall, it cascades down like a waterfall hence its long form name: Cascading Style Sheets.

If you imagine a standard HTML page structure, header, body and footer much like the human anatomy. And inside the body were three paragraph elements that looked something like this:

<p>Hello world!</p>
<p>Hello world!</p>
<p>Hello world!</p>

If I wanted to affect all three I might write some CSS like this:

<style>
p {
    color: red;
}
</style>

And it would affect all three paragraphs because the CSS is cascading from top to bottom much like the illustration of the waterfall.


But let’s say you wanted to emphasize the last paragraph different from the first two, what technique could you employ?


<style>
p {
    color: red;
}
p:last-child {
    font-size: 18px;
}
</style>

Now the last paragraph element will be red in colour but also the font size will be larger than the rest given that the default HTML font size is much smaller.


So then if CSS cascades down from top to bottom, how then does things become problematic?


CSS can become quickly problematic because of global selection. If your website for example uses many paragraphs than all those paragraphs will be affected by the same style in-which case a CSS battle pursues and the tendency is to fallback to !important to override this global style.


What are best practices? BEM is a good one to consider and if you are writing React code then you could create shareable CSS components.

6 views0 comments

Recent Posts

See All
bottom of page