CSS, Priorities, Selectors and Units

Syed Aquib AliSyed Aquib Ali
12 min read

CSS (Cascading Style Sheets)

CSS is a stylesheet language used to describe the presentation of a document written in HTML. CSS defines how elements should be displayed on screen, paper, in speech, or on other media. It allows web developers to separate the content (HTML) from the visual presentation (CSS), making it easier to maintain and update websites.

Features of CSS

  1. Separation of Content and Presentation: By using CSS, you can keep your HTML focused on the content while managing the design separately in CSS files.

  2. Control Layout and Design: CSS allows you to control the layout, colors, fonts, and overall look and feel of a website.

  3. Responsive Design: CSS enables the creation of responsive web designs that adapt to different screen sizes and devices.

  4. Re-usability: CSS styles can be re-used across multiple pages, making it easier to maintain consistency and update styles across a site.

CSS Priorities

CSS has three main ways to prioritize styling: inline styles, internal styles, and external stylesheets.

  1. Inline Styles

  • The priority of inline styles will be first, this style cannot be over written again in future anywhere else.

Inline styles are applied directly within HTML elements using the style attribute.

<h1 style="color: blue; text-align: center;">Hello, World!</h1>
<p style="color: green; font-size: 14px;">This is a paragraph with inline styles.</p>
  1. internal Styles

  • The priority of internal styles will be second after inline styles, this style can be over written again in future in inline styles only.

Internal styles are defined within the <style> tag inside the <head> section of the HTML document.

<head>
    <style>
        body {
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }
        h1 {
            color: blue;
            text-align: center;
        }
        p {
            color: green;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is a paragraph with internal styles.</p>
</body>
  1. External Stylesheets

  • The priority of external styles will be third and last after inline and internal styles, this style can be over written again in future in inline and internal styles.

    External stylesheets are linked to an HTML document using the <link> tag. This method is the most common and preferred because it separates content from presentation, making it easier to maintain and update in future.

  • Linking CSS in your HTML file:

<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
<!-- In the "href" write the name of your css file ex: href="mystyles.css"
-->
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is a paragraph with external styles.</p>
</body>
  • After creating and linking the CSS file into our HTML file, let's do some styling in the CSS file.
/* styles.css */
h1 {
    color: blue;
    text-align: center;
}

p {
    color: green;
    font-size: 14px;
}

NOTE: We try to always avoid using inline styling and internal styling, because HTML is only for making our skeleton structure and for our contents. It is the best practice to create and use our external stylesheets for better understanding, maintaining and re-using our styles.

CSS Selectors

CSS selectors are patterns used to select elements within an HTML document, allowing you to apply styles to them. There are several types of CSS selectors, each with its own specificity and use cases. Here’s a deep explanation of the most common types:

  1. Universal Selector (*)

    The universal selector selects all elements inside your HTML. It’s often used to apply a common style to all elements or to reset margins and padding.

* {
    margin: 0;
    padding: 0;
/* Resets the default spacing to zero */
}
  1. Element Selector

    The element selector targets elements based on their tag name. It applies the specified styles to all instances of that element.

/* Selects all <p> elements */
p {
    color: blue;
}
  1. Class Selector (.)

    The class selector targets elements based on their class attribute. Classes are reusable and can be applied to multiple elements.

/* Selects all elements with the class "example" */
.example {
    font-size: 20px;
}
<p class="example">This is a paragraph.</p>
<div class="example">This is a div.</div>
  • Using class is considered as best practice because we can re-use the same styling into different elements for the same styles.
  1. ID Selector (#)

    The ID selector targets a single element based on its ID attribute. IDs should be unique within a document, meaning an ID should only be applied to one element.

/* Selects the element with the ID "header" */
#header {
    background-color: lightgray;
}
  • We cannot re-use styles that are defined in ID's in other elements, we will have to create a new ID and copy-paste the styling to that new ID.
  1. Attribute Selector

    The attribute selector targets elements based on the presence or value of an attribute.

/* Selects all input elements with a type attribute value of "text" */
input[type="text"] {
    border: 1px solid #000;
}
<input type="text" placeholder="Enter text">
<input type="password" placeholder="Enter password">
  1. Descendant Selector

    The descendant selector targets elements that are descendants of a specified ancestor element. It selects all elements that are nested within the specified element.

/* Selects all <p> elements inside <div> elements */
div p {
    color: green;
}
<div>
    <p>This paragraph will be green.</p>
</div>
<p>This paragraph will not be green.</p>
  1. Child Selector (>)

    The child selector targets elements that are direct children of a specified element.

/* Selects all <p> elements that are direct children of <div> elements */
div > p {
    color: red;
}
<div>
    <p>This paragraph will be red.</p>
    <div>
        <p>This paragraph will not be red because it is a grandchild.</p>
    </div>
</div>
  1. Adjacent Sibling Selector (+)

    The adjacent sibling selector targets an element that is immediately preceded by a specified element.

/* Selects the <p> element immediately following an <h1> element */
h1 + p {
    margin-top: 0;
}
<h1>Heading</h1>
<p>This paragraph will have no top margin.</p>
<p>This paragraph will not be affected.</p>
  1. Pseudo-class Selector

    Pseudo-class selectors target elements based on their state or position.

/* Selects all <a> elements when they are hovered over */
a:hover {
    color: red;
}
<a href="#">Hover over me!</a>
  1. Pseudo-element Selector

    Pseudo-element selectors target parts of elements.

/* Selects the first line of a paragraph */
p::first-line {
    font-weight: bold;
}
<p>This is a paragraph. The first line will be bold.</p>
  1. Combining Selectors

    Selectors can be combined to target elements more precisely.

/* Selects all <p> elements with the class "highlight" that are children of <div> elements */
div p .highlight {
    background-color: yellow;
}
<div>
    <p class="highlight">This paragraph will be highlighted.</p>
    <p>This paragraph will not be highlighted.</p>
</div>

Understanding and using CSS selectors effectively allows you to precisely target and style elements in your HTML documents, making your web development process more efficient and your code more maintainable.

CSS Units

CSS size units are used to specify lengths, sizes, and distances in stylesheets. They fall into different categories based on how they measure dimensions: absolute units, relative units, and percentage units. Here's a deep explanation of each type:.

Absolute Units

Absolute units are fixed in size and are not affected by other elements or the viewport. They are best used when you need precise control over the size of an element.

  • px (Pixels): The most common unit, representing one pixel on the screen. Pixels are device-dependent and vary in size depending on the screen resolution.
p {
    font-size: 16px;
}

Relative Units

Relative units are based on the size of other elements, parents or the viewport. They are useful for creating responsive designs that adjust to different screen sizes and resolutions.

  • em: Relative to the font size of the element. If the parent element has a font size of 16px, then 1em is equal to 16px.
p {
    font-size: 2em; /* 32px if the parent font-size is 16px */
}
  • rem: Relative to the font size of the root element (usually the <html> element). If the root element has a font size of 16px, then 1rem is equal to 16px.
p {
    font-size: 1.5rem; /* 24px if the root font-size is 16px */
}
  • % (Percentage): Relative to the parent element's size. Commonly used for widths and heights.
div {
    width: 50%; /* 50% of the parent element's width */
}
  • vw (Viewport Width): Relative to 1% of the viewport's width. Useful for responsive designs.
div {
    width: 50vw; /* 50% of the viewport's width */
}
  • vh (Viewport Height): Relative to 1% of the viewport's height.
div {
    height: 50vh; /* 50% of the viewport's height */
}

Percentage Units

Percentage units are relative to the size of their parent element. They are commonly used for setting widths, heights, margins, and paddings.

.container {
    width: 100%; /* 100% of the parent element's width */
    height: 50%; /* 50% of the parent element's height */
}

.child {
    width: 50%; /* 50% of the .container's width */
    height: 100%; /* 100% of the .container's height */
}
<div class="container">
    <div class="child">This is a child element.</div>
</div>

Example with all units mentioned above:

body {
    font-size: 16px; /* Using px for base font size */
}

.container {
    width: 80%; /* Using percentage for width */
    padding: 2em; /* Using em for padding */
    margin: 1rem auto; /* Using rem for margin */
}

.box {
    width: 200px; /* Using px for fixed width */
    height: 50vh; /* Using vh for responsive height */
}

.text {
    font-size: 1.5em; /* Using em for relative font size */
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Units Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <div class="box">This box uses different units for size.</div>
        <p class="text">This text uses em units for font size.</p>
    </div>
</body>
</html>

Understanding the different CSS units and when to use them is essential for creating flexible, responsive, and well-designed web pages. Absolute units like px are useful for precise control, while relative units like em, rem, and percentages are key to responsive design. Viewport-based units like vw and vh help in creating layouts that adapt to different screen sizes.

(BONUS) CSS Properties

CSS properties are used to define styles for HTML elements. These properties control various aspects of an element's appearance and behavior, including layout, typography, colors, and more. Here are few CSS properties:

  1. Typography

  • font-family: Specifies the font of an element.
p {
    font-family: Arial, sans-serif;
}
  • font-size: Sets the size of the font.
p {
    font-size: 16px;
}
  • font-weight: Sets the weight (boldness) of the font.
p {
    font-weight: bold;
}
  • font-style: Sets the style of the font (e.g., italic).
p {
    font-style: italic;
}
  • text-align: Aligns the text inside an element.
p {
    text-align: center;
}
  • line-height: Sets the height between lines of text.
p {
    line-height: 1.5;
}
  • text-decoration: Adds decoration to text (e.g., underline, line-through).
p {
    text-decoration: underline;
}
  • color: Sets the color of the text.
p {
    color: red;
}
  1. Layout

  • width: Sets the width of an element.
div {
    width: 50%;
}
  • height: Sets the height of an element.
div {
    height: 200px;
}
  • margin: Sets the outer space of an element.
div {
    margin: 20px;
}
  • padding: Sets the inner space of an element.
div {
    padding: 20px;
}
  • border: Sets the border of an element.
div {
    border: 1px solid black;
}
  • display: Specifies the display behavior of an element.
div {
    display: none; /* block, inline, inline-block, etc. */
}
  • position: Specifies the positioning method of an element.
div {
    position: absolute; /* static, relative, absolute, fixed, sticky */
}
  • top, right, bottom, left: Specifies the offset of an absolutely positioned element.
div {
    position: absolute;
    top: 10px;
    left: 20px;
/* For position property it always gives us these "top, right, bottom 
and left" properties as well, to control our elements position.
}
  • float: Specifies whether an element should float to the left or right.
img {
    float: left;
}
  1. Box Model

  • box-sizing: Alters the default CSS box model.
div {
    box-sizing: border-box; /* content-box */
}
  • overflow: Specifies what happens if content overflows an element's box.
div {
    overflow: auto; /* visible, hidden, scroll */
}
  1. Backgrounds

  • background-color: Sets the background color of an element.
div {
    background-color: #f0f0f0;
}

background-image: Sets the background image of an element.

div {
    background-image: url('image.jpg');
}

background-repeat: Sets if/how the background image will repeat.

div {
    background-repeat: no-repeat; /* repeat, no-repeat, repeat-x,
    repeat-y */
}
  • background-size: Specifies the size of the background image.
div {
    background-size: cover; /* cover, contain, or specific dimensions */
}
  • background-position: Sets the initial position of the background image.
div {
    background-position: center;
}
  1. Borders

  • border: A shorthand property for setting all the border properties (width, style, and color).
div {
    border: 1px solid black;
 /* border: width style color; */
}
  • border-radius: Defines the radius of the element's corners.
div {
    border-radius: 10px;
}
  1. Flexbox

  • display: flex: Enables a flex container, providing a more efficient way to lay out, align, and distribute space among items in a container.
.container {
    display: flex;
}
  • justify-content: Defines how the browser distributes space between and around content items along the main-axis of a flex container.
.container {
    justify-content: center; /* flex-start, flex-end, space-between, space-around, space-evenly */
}
  • align-items: Aligns flex items along the cross-axis.
.container {
    align-items: center; /* flex-start, flex-end, stretch, baseline */
}
  • flex-direction: Specifies the direction of the flexible items (row, row-reverse, column, column-reverse).
.container {
    flex-direction: column;
}
  1. Grid

  • display: grid: Enables a grid container, allowing for layout of items in rows and columns.
.container {
    display: grid;
}
  • grid-template-columns: Defines the columns of the grid.
.container {
    grid-template-columns: 1fr 2fr 1fr; /* 3 columns with specified width fractions */
}
  • grid-template-rows: Defines the rows of the grid.
.container {
    grid-template-rows: auto 100px 1fr;
}
  • gap: Sets the gap between rows and columns.
.container {
    gap: 10px;
}
  1. Visibility and Display

  • visibility: Specifies whether an element is visible or not.
div {
    visibility: hidden;
}
  • display: Specifies the display behavior of an element.
div {
    display: none; /* block, inline, inline-block, flex, grid, etc. */
}

WHY WE USE CSS? : CSS properties provide a wide range of options to control the appearance and behavior of HTML elements. By understanding and utilizing these properties effectively, you can create visually appealing and responsive web designs.

1
Subscribe to my newsletter

Read articles from Syed Aquib Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Syed Aquib Ali
Syed Aquib Ali

I am a MERN stack developer who has learnt everything yet trying to polish his skills 🥂, I love backend more than frontend.