CSS fundamentals

August 24, 2022

Get the fundamentals down and the level of everything you do will rise
Michael Jordan

I decided to site MJ on purpose, as he is believed to be the GOAT, when it comes to basketball and arguably all sports. And yet he still believes in working consistently on improving and retaining fundamental skills.

The same applies to programming. It doesn’t matter what level of experience you have under your belt, it’s crucial to refine and improve basic knowledge of the craft.

For web development the trinity of fundamentals are HTML, CSS and JS. Today, I want to synthesize some basic CSS ideas.

Basics

To start it is crucial to differentiate styling elements with CSS rules and changing elements meaning with semantic HTML.

Although, using <em> tag will result in rendering a bold (emphasized) content inside, it’s not meant to style the text, but rather to format it, so the reader (User or robot) knows that the text inside is important. It also has an impact on availability and SEO.

On the other hand Cascading Style Sheets are meant to change the way elements are rendered on the page.

Rule

The most atomic part of CSS is rule, which consists of selector, property and its value:

selector {
    property: value
}

e.g.

body {
    color: #414141;
    background-color: #EEEEEE;
    font-size: 12px;
}

Linking style sheet

To place a set of rules wrote down in a stylesheet inside an HTML document, it has to be attached to a header:


<head>
  <meta charset="UTF-8" />
  <title>CSS fundamentals</title>
  <link rel="stylesheet" href="styles.css" />
</head>

Style cascade

Origins

User-agent, or browsers, have basic style sheets that give default styles to any document.

Author stylesheets are the most common type of style sheet - these are the styles written by web developers.

In most browsers, the user (or reader) of the website can choose to override styles using a custom user stylesheet designed to tailor the experience to the User’s wishes.

Importance

When a stylesheet includes an !important next to a property, styles take precedence, regardless of the specificity of the associated selector.

Specificity

Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element, which in turn, determines the property value to apply to the element. The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element and which is ignored.

Different rule weights led to creating rules of using CSS rules with the same specificity BEM. BEM attempts to make CSS rules more reusable by making everything a class selector.

Cascading Order

  1. Relevance
  2. Origin and importance
    1. user-agent (browser) normal
    2. user normal
    3. author (developer) normal
    4. CSS @keyframe animations
    5. author (developer) !important
    6. user !important
    7. user-agent (browser) !important
    8. CSS transitions
  3. Specificity
  4. Order of appearance

CSS box model

Block elements

Block boxes always appear below the previous block element. This is the “natural” or “static” flow of an HTML document when it gets rendered by a web browser. The width of block boxes is set automatically based on the width of its parent container. In this case, our blocks are always the width of the browser window.

Some examples of block elements.

Inline elements

Inline boxes don’t affect vertical spacing. They’re not for determining layout—they’re for styling stuff inside a block. The width of inline boxes is based on the content it contains, not the width of the parent element.

Some examples of inline elements.

Content, padding, border, margin

  • Content – The text, image, or other media content in the element.
  • Padding – The space between the box’s content and its border.
  • Border – The line between the box’s padding and margin.
  • Margin – The space between the box and surrounding boxes.

TIP: The margins of elements one with margin-bottom: 50px and the second with margin-top: 10px below won’t add up to 60px, but instead will overlap. To overcome this issue simply put an invisible (or empty) element between two collapsing margins. The alternatives are using padding when possible, using top-only or bottom-only margin policy, or using flexbox

Content boxes vs border boxes

Content box is default behaviour, and it applies dimensions (width, height) to content only, omitting padding and border dimensions, which can be a little counterintuitive when laying out a page.

Solution is utilizing box-sizing: border-box.

div {
    color: #FFF;
    background-color: #5995DA;
    padding: 20px;
    border: 2px solid #5D6063;

    width: 200px;
    box-sizing: border-box; /* This will apply width to content + padding + border line width */
} 

Selectors

Classes

Class selectors group CSS rules and apply them to multiple HTML elements. They differentiate HTML elements of the same type.

.submit {
    background-color: deepskyblue;
    border-radius: 5px;
    font-style: italic;
}
<button class="submit"
        type="button">
  Submit
</button>

Multiple classes can be applied to the same element.

I also suggest learning a concept of pseudo classes.

ID selectors

ID selectors are a more precise alternative to class selectors. There is only one element with the same ID allowed per page, which means its styles can’t be reused. Instead of a class attribute, they require an id attribute on whatever HTML element you’re trying to select.

#one-of-a-kind-button { /* id definition */
    color: coral;
}
<a id="one-of-a-kind-button" class="button" href="somewhere.html">One and only</a>

IDs as URL fragments

ID attributes must be unique because they serve as the target for “URL fragments”. Fragments point to a specific part of a web page. They look like an ID selector applied the end of a URL.

Relative units of measurement

The em unit is very useful for defining sizes relative to some base font. In the above example, font size is 12px, so any font size defined with em will be a multiplication of this base size e.g.

h1 {
    font-size: 2em;
}

will result in headings sized 24px.

Common layouts

Flexbox

The most commonly used layout is flexbox. Flexbox is a one-dimensional layout method for arranging items in rows or columns. Items flex (expand) to fill additional space or shrink to fit into smaller spaces. It definitely deserves its own article, so I’m going to refer to complete guide.

Grid

CSS Grid Layout excels at dividing a page into major regions or defining the relationship in terms of size, position, and layer, between parts of a control built from HTML primitives.

Like tables, grid layout enables an author to align elements into columns and rows. However, many more layouts are either possible or easier with CSS grid than they were with tables. For example, a grid container’s child elements could position themselves so they actually overlap and layer, similar to CSS positioned elements. Please refer to complete guide.

Summary

  • Everything is a box.
  • Boxes can be inline or block-level.
  • Boxes have content, padding, borders, and margins.
  • They also have seemingly arbitrary rules about how they interact.

Mastering fundamentals improves understanding of more complex and commonly used page layouts such as CSS grid and flexbox. Learning basic concepts behind technology we use on a daily basis can speed up problem-solving.

Further reading:

  1. MDN CSS Reference
  2. Block elements
  3. Inline elements
  4. BEM
  5. Great fundamentals of HTML and CSS
  6. Complete guide to flexbox
  7. Complete guide to grid
  8. Centering elements

Profile picture

Written by Jacek Malczyk software engineer based in Warsaw, clean coder, ReactJS enthusiast.

© 2022