CSS Basics for newbs

CSS Basics for newbs

Get a quick overview and introduction of CSS and all the basic theory you need to know, make sure to visit MDN Docs for more in-depth CSS topics.


What is CSS ?

CSS stands for cascading style sheets, CSS is the secret to making your web pages look amazing. Currently, CSS is the only way to style web pages in all its different forms. In this article, I cover some basic theory of CSS every web developer needs to know. Now CSS goes much deeper than this and can get very complicated very quickly, but most of the time you will only need the basics.

How does css work?

Magic! Well, not really, it can feel like that sometimes. So Browsers are responsible for loading the CSS and are very complicated pieces of software but here is a simple breakdown of how it works thanks from our friends over at MDN :

  1. The browser loads the HTML (e.g. receives it from the network).
  2. It converts the HTML into a DOM (Document Object Model). The DOM represents the document in the computer's memory. The DOM is explained in a bit more detail in the next section.
  3. The browser then fetches most of the resources that are linked to by the HTML document, such as embedded images and videos ... and linked CSS! JavaScript is handled a bit later on in the process, and we won't talk about it here to keep things simpler.
  4. The browser parses the fetched CSS, and sorts the different rules by their selector types into different "buckets", e.g. element, class, ID, and so on. Based on the selectors it finds, it works out which rules should be applied to which nodes in the DOM, and attaches style to them as required (this intermediate step is called a render tree).
  5. The render tree is laid out in the structure it should appear in after the rules have been applied to it.
  6. The visual display of the page is shown on the screen (this stage is called painting).

The following diagram also offers a simple view of the process.

rendering

Getting Started with CSS

The quickest way to get started with CSS is right inside your HTML. Open your favourite code editor and create a new index.html file. Copy the below CSS into your HTML file:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>CSS for newbs</title>

</head>

<body>
    <h1>CSS for newbs</h1>
</body>
</html>

Save it and double click on the file to open it in your browser.

To style this document, you only need one line of code:

<h1 style="color: blue;">CSS for newbs</h1>

Notice how the color changed, lets break it down:

Inside the first HTML tag, we added a property called style, this is the standard way of adding what we call inline styles, the easiest and most direct way of adding CSS to any HTML element. We will breakdown the CSS syntax a bit later. For now, try and make the body's background colour yellow.

Using CSS

There are a few ways to use CSS with HTML. We covered the first and easiest way above by using inline styles. Additionally and the preferred way is to use a stylesheet.

A style sheet is an external css file that contains all of your css. This file is then linked to your HTML document. This is a more clean and industry-standard way of writing your css.

Let's add a stylesheet to our documents. first, add this line of code above the < /head > closing tag to link the style sheet to our HTML document.

<link rel="stylesheet" href="style.css">

Next, delete the style from the h1 including the property. Create a new file in your directory called style.css. Great, you just created your stylesheet and it is now linked to your document!

CSS Basics

Before we jump into the stylesheet, we need to go over some of the basics of CSS. We need to know how it actually works and how we write it down.

p {
    color : white;
    }

So here we have a simple CSS statement that makes the colour of all text wrapped in tags white, how do I know this? I can read CSS, its very simple:

  • First, we have the p this is what we call a selector
  • { always followed by an opening bracket
  • colour: this is the property we wish to change, always followed by a colon
  • white is the value of that property, each property has its own preferred and valid value that we can use.
  • each time we have done with the property and value assignment we close it with a semicolon ;
  • and remember your closing bracket

This is the same basic rules you will follow for writing any CSS styles, of course, it can get more complicated, but the rules always stays the same.

Selectors

We use selectors to target specific elements or element that we wish to style. There are a wide variety of CSS selectors available.

As taken from the MDN Docs:

There are a few different groupings of selectors, and knowing which type of selector you might need will help you to find the right tool for the job. In this article's sub-articles we will look at the different groups of selectors in more detail.

Type, class, and ID selectors

This group includes selectors that target an HTML element such as an h1.

h1 { }

It also includes selectors which target a class:

.box { }

or, an ID:

#unique { }

Attribute selectors

This group of selectors gives you different ways to select elements based on the presence of a certain attribute on an element:

a[title] { }

Or even make a selection based on the presence of an attribute with a particular value:

a[href="https://example.com"] { }

Pseudo-classes and pseudo-elements

This group of selectors includes pseudo-classes, which style certain states of an element. The :hover pseudo-class for example selects an element only when it is being hovered over by the mouse pointer:

a:hover { }

It also includes pseudo-elements, which select a certain part of an element rather than the element itself. For example, ::first-line always selects the first line of text inside an element (a < p >" in the below case), acting as if a < span > was wrapped around the first formatted line and then selected.

p::first-line { }

Combinators

The final group of selectors combine other selectors in order to target elements within our documents. The following for example selects paragraphs that are direct children of < article > elements using the child combinator (>):

article > p { }

Selector lists

If you have more than one thing which uses the same CSS then the individual selectors can be combined into a selector list so that the rule is applied to all of the individual selectors. For example, if I have the same CSS for an h1 and also a class of .special, I could write this as two separate rules.

h1 {
  color: blue;
}

.special {
  color: blue;
} 

I could also combine these into a selector list, by adding a comma between them.

h1, .special {
  color: blue;
} 

White space is valid before or after the comma. You may also find the selectors more readable if each is on a new line.

h1,
.special {
  color: blue;
} 

Inheritance & Specificity

Specificity is CSS way of knowing what styles to apply when, for example lets say you have an h1 with a class and an ID.

Example

<h1 id="hello" class="myTag" >Hello</h1>

Stylesheet:

h1 {
    color : green;
}

#hello {
    color : blue;
}

.myTag {
color : yellow;
}

So can you guess which style will be applied?

Well don't guess here is the rules:

Calculating CSS Specificity Value:

  • If the element has inline styling, that automatically wins (1000 points)
  • For each ID value, apply 100 points
  • For each class value (or pseudo-class or attribute selector), apply 10 points
  • For each element reference, apply 1 point

Highest value wins.

So for the above example the ID would win because it has 100 points, If we were to add an inline style it would trump all other selectors and win.

Inheritance

Inheritance also needs to be understood in this context — some CSS property values set on parent elements are inherited by their child elements, and some aren't.

For example, if you set a color and font-family on an element, every element inside it will also be styled with that color and font, unless you've applied different color and font values directly to them.

Box-Model

In CSS everything is a box. How these boxes behave is what we call the box-model. In order to create some great layouts you need to understand CSS Box-Model. There are two types of boxes, inline boxes and block boxes. let's see how they behave:

from MDN:

Block and inline boxes

In CSS we broadly have two types of boxes — block boxes and inline boxes. These characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page:

If a box is defined as a block, it will behave in the following ways:

  • The box will break onto a new line.
  • The box will extend in the inline direction to fill the space available in its container. In most cases this means that the box will become as wide as its container, filling up 100% of the space available.
  • The width and height properties are respected.
  • Padding, margin and border will cause other elements to be pushed away from the box

Unless we decide to change the display type to inline, elements such as headings (e.g. < h1 >) and < p > all use block as their outer display type by default.

If a box has an outer display type of inline, then:

  • The box will not break onto a new line.
  • The width and height properties will not apply.
  • Vertical padding, margins, and borders will apply but will not cause other inline boxes to move away from the box.
  • Horizontal padding, margins, and borders will apply and will cause other inline boxes to move away from the box.

The < a > element, used for links, < span >, < em > and < strong > are all examples of elements that will display inline by default.

The type of box applied to an element is defined by display property values such as block and inline, and relates to the outer value of display.

The full CSS box model applies to block boxes, inline boxes only use some of the behavior defined in the box model. The model defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on the page. To add some additional complexity, there is a standard and an alternate box model.

Parts of a box

Making up a block box in CSS we have the:

  • Content box: The area where your content is displayed, which can be sized using properties like width and height.
  • Padding box: The padding sits around the content as white space; its size can be controlled using padding and related properties.
  • Border box: The border box wraps the content and any padding. Its size and style can be controlled using border and related properties.
  • Margin box: The margin is the outermost layer, wrapping the content, padding and border as whitespace between this box and other elements. Its size can be controlled using margin and related properties.

The below diagram shows these layers:

box-model

The standard CSS box model

In the standard box model, if you give a box a width and a height attribute, this defines the width and height of the content box. Any padding and border is then added to that width and height to get the total size taken up by the box. This is shown in the image below.

If we assume that the box has the following CSS defining width, height, margin, border, and padding:

.box {
  width: 350px;
  height: 150px;
  margin: 10px;
  padding: 25px;
  border: 5px solid black;
}

The space taken up by our box using the standard box model will actually be 410px (350 + 25 + 25 + 5 + 5), and the height 210px (150 + 25 + 25 + 5 + 5), as the padding and border are added to the width used for the content box.

standard-box-model

Note: The margin is not counted towards the actual size of the box — sure, it affects the total space that the box will take up on the page, but only the space outside the box. The box's area stops at the border — it does not extend into the margin.

Using display: inline-block

There is a special value of display, which provides a middle ground between inline and block. This is useful for situations where you do not want an item to break onto a new line, but do want it to respect width and height and avoid the overlapping seen above.

An element with display: inline-block does a subset of the block things we already know about:

  • The width and height properties are respected.
  • padding, margin, and border will cause other elements to be pushed away from the box.

It does not, however, break onto a new line, and will only become larger than its content if you explicitly add width and height properties.

Thank you be sure to check out the MDN Docs for more CSS tutorials

Show Comments