CSS: Websites Saving Grace
Photo by @der_maik_ - unsplash.com

CSS: Websites Saving Grace

Firstly, I would like to provide my foundational points for statement provided in the title and post of this article.

Aesthetics is everything, especially in the modern world, where appearances are prioritised and placed upon a pedastle. So, taking this viewpoint it is my belief that if websites still looked like they were 20 years ago at the advent of the WWW, websites and web development would have faltered and had a gradual decline into extinction. Widespread adoption and accessibility for creatives to enter the world of the web would be zilch.

Secondly, I would advise checking out my latest article here, before continuing as aspects covered in this article expand upon ideologies already explored within that article.

Again, as stated in last article, for disoriented users who are trying to figure out where in the website ecosystem presented in this article we currently are discussing. We are dissecting the "client" component of this system, pulling apart the technologies available for use to make the front end facing part of a website.


What is CSS ?

As CSS is such a vast topic, we will delve into the language of CSS in a number of articles. In this article, we will cover the abstract points to understand in reference to CSS:

  • What is CSS
  • How to include CSS in your webpage - Inline, externally, or internally
  • What is the notion of specificity - ids, classes, modules
  • Bootstrap and Tailwind - utility classes


What is CSS ?

As previously pointed out in previous articles, CSS enables us the freedom and expression of adding style to our website. Once we lift the complete code from the last article on HTML and insert it into any online IDE - integrated development environment (ie. platform that enables you to write code), we observe a similar display to below:

No alt text provided for this image
Display of rendered HTML from latest article


This is unsightly and not aesthetically pleasing in any shape or form. The webpage is dull, boring and languid. So, the advent of CSS was required.

Cascasing Style Sheets or commonly referred to as CSS is a style-sheet language which allows us a method by which to add an improved appearance to our websites.


How do we include it in our website ?

After the depiction above, you may be wondering how to make CSS operational upon our website.

There are a few methods by which to include CSS in your website.


Inline Styling

Inline styling, which is a form of styling by directly applying style to the elements of your webpage by baking it into the HTML element required. As discussed in the aforementioned HTML article, attributes allow us to attach operational or informational functionalities to an element. In this case, an operational attribute is necessary. Use of the HTML attribute "style" on any element makes this possible.

Let's take the title of the page in picture above as an example and change its colour.

Formally,

<h1>Title of page</h1>        

With our change,

<h1 style="color: blue;">Title of page</h1>        
No alt text provided for this image

A few things to note:

  1. Style attributes take a string value which must be enclosed in ""
  2. The properties of CSS follow American English spelling
  3. If property is two words, the individual words are adjoined with a "-"
  4. Every property has a definite amount of values from which to choose
  5. Each property and respective associated value is called a style rule.
  6. Every style rule must be ended with a ;


So, if multiple style rules are needed for example to make the title uppercase and blue, you would apply the style as follows:

<h1 style="color: blue; text-transform:uppercase;">Title of page</h1>        
No alt text provided for this image

Now imagine, you have a lot of style rules to attach to a certain element and/or every element on the page needs styling. This would become a tedious process, messy and would amount to unreadable code. This is the reason the two next styling procedures were established.

Before discoursing these processes, a step back is needed to obtain an understanding as to what is an id and a class.


What is a specifier ?

A specifier can be the thought of as a reference point which can be attached to or explicitly picked from any element on a webpage. In CSS terms, there is a few types of specifiers:

  • Tag name
  • Class
  • Id (ie. identifier)

These specifiers can then be utilised as a means of identification of the element to which the style rules need be applied.


Tag name

Tag name refers to the application of styling to the HTML element by the utilisation of the tag name desired.

<h1>Title of page</h1>        
No alt text provided for this image


Class

Class refers to the use of a particular reference attribute called "class". This is attached to the desired HTML element for styling purposes ( but can be used in JS for identification purposes also as we will see in later articles ). Upon deploying use of the class specifier in CSS, we can liken class:title to equal .title

<h1 class="title">Title of page</h1>        
No alt text provided for this image


Id

Id refers to the use of a different reference attribute named "id". It is very similar in design to the class specifier and can be adopted for styling a HTML element like all above. Upon deploying use of the class specifier in CSS, we can liken id:title to equal #title

<h1 id="title">Title of page</h1>        
No alt text provided for this image


The main difference between use of "id" and the others specifiers is that there's a possibility of using the same attribute values for other specifiers in multiple places in a webpage. With an id specifier, the convention dictates that its value can only be attributed to one element in the webpage (ie. you can't repeat the same id attribute values across elements on a webpage).

<h1 id="title">Title of the page</h1>
<h3 class="product-header">Product 1</h3> 
<h3 class="product-header">Product 2</h3>        


Internal Styling

With that out of the way, a resumption of the styling methods can commence. The next up is internal styling. Internal and external (discussed next) styling assume prior identification specifiers are in place in the HTML necessary to be styled.

The earlier HTML article refers to the fact that style rules can be placed directly inside the head tag of the HTML page. Essentially, this is the basis of inline styling. Let's take the above example of the title and adopt this principle:

<head>
  <title>Website Page Name</title>
  <meta content="width=device-width, initial-scale=1" name="viewport" />
  <meta name="description" content="This is a website description for SEO purposes" />
  <link rel="icon" href="/favicon.ico" />
  <script defer src="main.js"></script>
  <style>
     #title {
       color: blue;
       text-transform: uppercase;
     }
     .header {
       color: red;
     }
  </style>
</head>
<body>
   <h1 id="title">Title of page</h1>
   <h3 class="header">Secondary header</h3>
</body>        
No alt text provided for this image

Observed is the fact that the "id:title" in CSS is referenced as #title while "class:header" is denoted as .header. All style rules in CSS associated with a particular element are enclosed within {} and again, every style rule is finished with a respective ;


A big concept in programming paradigms is the notion "separation of concerns". You will see reference to this everywhere discussing DRY(acronym for Don't Repeat Yourself) and clean code. Code that is DRY is modular and containerized, where single units of a program perform specific singular functionalities. The beneficial aspects of this are numerous and far outweigh intertwining, dependent and developing tightly coupled code. With this way of styling we are not adhering to this ideology (ie. our HTML and CSS are intermingling in one file).

This is the necessity for external styling.


External styling

External styling involves an abstraction of the CSS necessary to style the website into its own file. The CSS logic is the exact same as above, in that tagging elements with specifiers is still necessary and the style rules are identical to ones implemented above. However, the big difference is the style tag in the head section of the webpage is replaced with a link tag like this:

From:

<head
  <title>Website Page Name</title>
  <meta content="width=device-width, initial-scale=1" name="viewport" />
  <meta name="description" content="This is a website description for SEO purposes" />
  <link rel="icon" href="/favicon.ico" />
  <script defer src="main.js"></script>
  <style>
     #title {
       color: blue;
       text-transform: uppercase;
     }
     .header {
       color: red;
     }
  </style>
</head>
<body>
   <h1 id="title">Title of page</h1>
   <h3 class="header">Secondary header</h3>
</body>>        

To:

-- index.html --

<head>
? <title>Website Page Name</title>
? <meta content="width=device-width, initial-scale=1" name="viewport" />
? <meta name="description" content="This is a website description for SEO purposes" />
? <link rel="icon" href="/favicon.ico" />
  <link rel="stylesheet" href="main.css">
? <script defer src="main.js"></script>
</head>
<body>
? ?<h1 id="title">Title of page</h1>
? ?<h3 class="header">Secondary header</h3>
</body>

-- main.css --

#title {
  color: blue;
  text-transform: uppercase;
}
.header {
  color: red;
}         

This doctrine conforms more reasonably to the concept of clean code and thus is used more extensively throughout development in large-scale web applications. This avoids headaches in later development and sets in place a sense of organisation to your code.

The code and output is still the same.

No alt text provided for this image


What is specificity in CSS ?

This term is used quite often when explaining CSS, it is attributed to the use of the specifiers indicated above. The term relates to the decision of which is the deciding specifier if multiple are used on a single element. Take these three examples for reference:

-- index.html --

<h1 class="title" id="title">Title of the page</h1>

-- main.css --

h1 {
  color: blue;
}

.title {
  color: yellow;
}

#title {
  color: red;
}        

2.

-- index.html --

<h1 class="title" id="title">Title of the page</h1>

-- main.css --

h1 {
  color: blue;
}

#title {
  color: red;
}

.title {
  color: yellow;
}        

3.

-- index.html --

<h1 class="title" id="title">Title of the page</h1>
<h1>No styling should be applied here</h1>

-- main.cs --

h1 {
? color: blue;
}


.title{
? color: yellow;
}


#title {
? color: purple;
}        


What will be observed as output in these three scenarios ?

No alt text provided for this image

Upon careful observation of the above code you may think that the reason for this output is that the order of the style rules in the CSS file matter. While this is partially correct, 2 depicts that there's another factor at play here.


2.

No alt text provided for this image

Note: Style rule for "id" being raised higher than "class" for this example.

The underlying factor that leads to this output can be explained as such:

  1. id's
  2. classes
  3. tags

in order of importance to being the deciding style rule for the element desired.


3.

No alt text provided for this image

Number 3 highlights a problem with specificity in that if no higher power specifier is applied to a tag it will default to the tag style rule for that particular element, which in this case was the colour of blue.


So, how can we overcome this problem ?

The problem depends on factors such as reusability of code across webpages, scale of your website and so on.

  1. One consideration and mostly used in web development is to use tags as a specifier sparsely. Use classes and ids more frequently.
  2. Use different class attribute values across your application.
  3. If use of same specifier(ie. tags and classes) is unavoidable, consider use of a css selector (which we will cover in next article) in front or after the tag.
  4. Another method which I would advise against as it leads to all sorts of confusion and introduces bugs would be to introduce the use of !important flag to override previously set style rules. It can be shown like this:

-- index.html --

<h1 id="title">Title</h1>
<h1 class="title">Introducing higher specifity than ids</h1>

-- main.css --

#title {
  color: blue;
}

.title {
  color: red !important;
}        
No alt text provided for this image

This can be handy when dealing with prior imported third party stylesheets that already have certain style rules implemented for specific class attribute values but let me pose a question to you to explain the problem you would run into:

How do you override a style rule enforced with an !important flag ? Short answer is you can't so this leads to problems down the line.


CSS Layers

Another solution would be the introduction and usability of CSS layers in our codebase. This is a fairly new concept to CSS, where you abstract the importance of the specificity into layers rather than the specifiers themselves. If you imagine this concept like a lasagne where one sheet adds another layer of styling to the element this may be more comprehensible.

To expand, lets consider we want to style a button in CSS.

By declaring, <button></button> in your HTML without any accompanying stylesheet or style rules, the browser has already attached its built in "user agent stylesheet" or layer of styles to the button. This applies the default style rules for the button specifier tag name like this:

-- user-agent-stylesheet -- (baked into browser)

button {
  border-radius: 20px;
  border: 1px solid #eee;
}        

Note: Each browser has a different set of default style rules. So, this is why a default rendered button in Chrome make look completely different to a button rendered in Safari.

So let's say we add our own style accordingly:

-- main.css --
button {
  border-radius: 20px;
  border: 1px solid #eee;
  color: blue;
}        

We have essentially created this picture:

No alt text provided for this image

Where the layers of style rules have the order of specificity:

No alt text provided for this image

So this is the default case where custom-stylesheet can be any stylesheet we add with style rules (ie. main.css)

The new @layer property enables us the ability to further segment our custom-stylesheets into their own layers and give them an order of specificity.

This is particularly useful when dealing with third party stylesheets and rules provided by libraries such as Bootstrap.

The order of specificity follows:

  1. Non-layer style rules
  2. Custom layer style rules - where order matters of these layers themselves
  3. Browser layer style rules

Lets see it in action:

@layer base {
  html, body{
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }
}

@layer utilities {
  a{ 
    text-decoration: none;
    color: black;
  }
}

button {
 color: blue;
}        

By default as stated above, order in custom layers flows from bottom to top, where bottom is provided more importance so now we have

  1. Non-layered code
  2. Utilities
  3. Base
  4. Browser layer

Let's add a bootstrap style layer:

@import url("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css");
layer(framework)

@layer base {
  html, body{
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }
  button{
   color: red;
  }
}

@layer utilities {
  a{ 
    text-decoration: none;
    color: black;
  }
  button{
   color: purple;
  }
}

button {
 color: blue;
}        

Few things to note:

  1. @import url is achieving the same thing as adding a link tag with the href as value contained within the enclosing "" to the head tag in HTML.

<head>
  <link >
  <link href="main.css">
</head>        

but instead of having two links to two different stylesheets, we are able to import the stylesheet required into the other to leave our head tag like:

<head
  <link href="main.css">
</head>>        

and the @import statement as above.

2. Bootstrap is imported from a CDN. This topic will be covered in a further article. Essentially, just the bootstrap predefined stylesheet same as we are defining now though.

3. We are importing the bootstrap style rules and containerising the rules in its own self enclosing layer named "framework".

So now our order of specificity looks like:

  1. Non-layered code (ie. CS)
  2. Utilities
  3. Base
  4. Framework
  5. Browser layer (UAS)

No alt text provided for this image
No alt text provided for this image

Remove the CS styling:

@import url("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css")
layer(framework)

@layer base {
  html, body{
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }
  button{
   color: red;
  }
}

@layer utilities {
  a{ 
    text-decoration: none;
    color: black;
  }
  button{
   color: purple;
  }
}        

The ending result:

No alt text provided for this image


What is Bootstrap and Tailwind.CSS ?

I've mentioned Bootstrap a few times throughout the last section, so I thought it only right to give you a brief overview before closing this article on Bootstrap and Tailwind.CSS.

Bootstrap and Tailwind.CSS are respective utility libraries and frameworks which aid in quick prototyping and provide a ready made component and utility class repertoire for use if you so wish. They provide their own stylesheets which have to be imported into your website.

Both frameworks and libraries mentioned have their place and pluses and minuses but overall they're handy tools to have knowledge about.

要查看或添加评论,请登录

Adam O' Ceallaigh的更多文章

  • UI Recreations: LinkedIn

    UI Recreations: LinkedIn

    Prerequisites If you haven't already, be sure to give my latest UI recreation of Pinterest a look. In that article I…

  • UI Recreations: Pinterest

    UI Recreations: Pinterest

    Prerequisites If you haven't already, make sure to check out my latest recreation: Instagram . While being a…

  • UI Recreations: Instagram

    UI Recreations: Instagram

    Prerequisites Prior knowledge of HTML and CSS is required before continuation of this article. In particular, HTML:…

  • UI Recreations: Tiktok

    UI Recreations: Tiktok

    Prerequisites Firstly, I would like to preface this article by suggesting a checkout of a few others prior to…

  • UI Recreations: Netflix

    UI Recreations: Netflix

    In my latest article CSS: Websites Saving Grace (Part 4), I previewed and displayed various examples of popularised…

  • CSS: Supercharge your workflow with advanced features

    CSS: Supercharge your workflow with advanced features

    If you haven't already, I invite you to check out my latest article titled "CSS: Websites Saving Grace (Part 4)". The…

  • CSS: Websites Saving Grace (Part 4)

    CSS: Websites Saving Grace (Part 4)

    Prerequisites Prior reading of HTML: "Here's The Main Layout", CSS: Websites Saving Grace and CSS: Websites Saving…

  • CSS: Websites Saving Grace (Part 3)

    CSS: Websites Saving Grace (Part 3)

    For first-time viewers and readers of this series "Pulling Programming Apart", it is advised to check out previous…

  • CSS: Websites Saving Grace (Part 2)

    CSS: Websites Saving Grace (Part 2)

    If you haven't already, check out CSS: Websites Saving Grace (Part 1) available here. The linked article deals with the…

  • HTML: "Here's The Main Layout"

    HTML: "Here's The Main Layout"

    Firstly, if you haven't checked out my previous article here. I would recommend doing so before continuing, as it aims…

社区洞察

其他会员也浏览了