What Is CSS – Cascading Style Sheets Explained

What Is CSS

A Cascading Style Sheet Tutorial – What Is CSS and Why It Is Essential for Web Design?

CSS, or Cascading Style Sheets, is a fundamental component of web development that plays a crucial role in creating visually appealing and engaging websites. But what exactly is CSS, and why is it essential for web design? In this comprehensive guide, we will explore the ins and outs of CSS, its functionalities, and how it enhances the overall user experience.

We will delve into the world of CSS style sheets and discover how they can revolutionize the way you design web pages. From understanding the basics of CSS to leveraging its advanced features, this guide will equip you with the knowledge and skills needed to enhance the visual appeal and functionality of your websites.

What is CSS? – Cascading Style Sheets Explained

CSS is a markup language used in conjunction with HTML to style and format web page elements. It provides developers with the ability to define the visual appearance of various elements, such as fonts, colors, layouts, and more. By separating the content from its presentation, CSS allows for flexibility and consistency throughout a website.

What is the difference between Inline CSS, External CSS, or Internal CSS

Inline CSS – Change HTML Styles Within The HTML

Inline CSS refers to the practice of embedding CSS styles directly into HTML elements, allowing you to apply specific styles to individual elements without the need for a separate CSS file. It’s like giving your HTML code a personal touch with a sprinkle of style! With inline CSS, you can make swift changes and experiment with different styles effortlessly. This approach is especially handy when you want to customize a single element or override existing styles. Just remember, while inline CSS can be convenient, relying too heavily on it can lead to tangled HTML code and make maintaining your website a tad trickier. So, use it wisely and sparingly, and your website will be bathing in style with a touch of ease!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline CSS Example</title>
</head>
<body>
    <!-- Inline CSS applied to individual elements -->
    <h1 style="color: blue; text-align: center;">Welcome to My Website</h1>

    <p style="font-size: 18px; line-height: 1.5; color: #333;">This is a sample webpage with inline styles.</p>

    <div style="background-color: #f0f0f0; padding: 10px;">
        <p style="color: green;">This is a paragraph with a green colour within a light grey background.</p>
    </div>

    <!-- Alternatively, you can apply styles to multiple elements with a single style attribute -->
    <div style="border: 2px solid #e74c3c; padding: 10px; margin-top: 20px;">
        <p style="color: #e74c3c; font-weight: bold;">This paragraph has a red border and bold red text.</p>
        <p style="color: #3498db; font-style: italic;">This paragraph has a blue color and italic style.</p>
    </div>
</body>
</html>

External CSS  – Connecting to a Separate CSS File

With external CSS, you can keep all your style rules separate from your HTML code, making it easier to navigate and update. No more sifting through endless lines of HTML to make a small design tweak! Simply link your external CSS file to your HTML document, and voila! You can now style your website with ease, using classes and IDs to target specific elements. So, say goodbye to tangled code and hello to cleaner, more organized styling with external CSS.

Internal CSS – CSS and HTML in One HTML Page

With internal CSS, you can define your styles right inside the head section of your HTML file or above the section it relates to, without needing to create an external style sheet. This means you can keep all your styling information neatly organized and easily accessible within your webpage. It’s perfect for smaller projects or when you want to quickly make some visual tweaks to a specific page. 

So if you’re looking for a user-friendly way to personalize the appearance of your website, internal CSS is worth exploring and a method I often use myself.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal CSS Example</title>

    <!-- Internal CSS within a <style> block -->
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f4f4;
            color: #333;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #3498db;
            color: #fff;
            padding: 10px;
            text-align: center;
        }

        .container {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
        }

        h1 {
            color: #2ecc71;
        }

        p {
            font-size: 16px;
            line-height: 1.5;
        }

        .highlight {
            background-color: #ffeb3b;
            padding: 5px;
        }
    </style>
</head>
<body>
    <!-- HTML content goes here -->
    <header>
        <h1>Welcome to My Website</h1>
    </header>

<!--section1-->

<style>

sectionOne {margin:100px 50px;}

.red-font {color:red;}

</style>

<section id=sectionOne>

    <div class="container">
        <p class="red-font">This is a sample webpage with internal CSS for styling.</p>
        <p class="highlight">This paragraph has a yellow background.</p>
    </div>

</section>
</body>
</html>

Fonts

With CSS, you can easily customize the way your text looks, making it stand out and reflect your brand’s voice. Whether you want to change the font family, size, color, or even add some fancy effects like shadows or gradients, CSS has got your back. By simply selecting the element you want to style and applying some easy-to-understand properties, you can turn plain and boring text into something captivating and eye-catching. So go ahead and explore the vast world of CSS fonts, and let your creativity shine through!

Choosing a font family with CSS

We have a couple of guides on actually choosing a font for your website project here.

Choosing the Correct Webfont for Your Project

Website Typography – Comprehensive Guide

But once you have chosen your font you need to add and set it to a particular text type such as header or body text. Below are some examples on how to add and set fonts in css.

Using Font-face

Font face method is perfect for using fonts you have uploaded with the website as you set the path to the font file and provide it with a name. Then you simply apply that given name to the type of font (header or body text).

@font-face {
  font-family: 'CustomFont';
  src: url('path/to/font.ttf') format('truetype'); /* Change the path and format accordingly */
}

body {
  font-family: 'CustomFont', sans-serif; /* Use the custom font */
}

Google Fonts

Google fonts can be downloaded from Google and then uploaded to the website in which case you can use the font-face method above. However, Google also allows you to link to their font so you don’t need to upload it. In this case, the CSS is slightly different as shown in the example below.

/* Include the Google Fonts link in your HTML file */
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

/* Use the font in your CSS file */
body {
  font-family: 'Roboto', sans-serif;
}

Font Styles with CSS 

CSS is used to style fonts also. You can change font-size, font-weight (how bold you want the font), font-color (colour), font-style etc. Below are some CSS values to give you an understanding of what css properties can do.

Colour

.color-example {
  color: red;
}

font-size: Sets the size of the text.

.font-size-example {
  font-size: 16px;
}

font-weight: Sets the thickness of the text.

.font-weight-example { font-weight: bold; }

//or 

.font-weight-example { font-weight: 700; }

//notice you can apply values in sets of 100. 100 being the thinnest/finest and 900 being the boldest.

text-align: Sets the alignment of the text.

//align text from the center

.text-align-example {
  text-align: center;
}

//align text from the left (default)

.text-align-example {
  text-align: left;
}

//align text from the right

.text-align-example {
  text-align: rignt;
}

//align text justified so that the paragraph align left and right in blocks. A word of caution this looks better on larger screens so i would recommend using @media queries to set it on larger screens (the below example will only display on screens with at least 1028 pixes wide otherwise the text will be aligned to the left.

.text-align-example {
  text-align: left;
}

@media (min-width:1028px){

.text-align-example {
  text-align: justify; }

}

text-decoration: Sets decoration properties for the text (e.g., underline, line-through).

.text-decoration-example {
  text-decoration: underline;
}

line-height: Sets the height of each line of text.

.line-height-example {
  line-height: 1.5;
}

letter-spacing: Sets the spacing between characters.

.letter-spacing-example {
  letter-spacing: 1px;
}

word-spacing: Sets the spacing between words.

.word-spacing-example {
  word-spacing: 2px;
}

text-transform: Sets the capitalization of the text.

.text-transform-example {
  text-transform: uppercase;
}

CSS Border

border-style: Sets the style of the border (e.g., solid, dashed, dotted).

.border-style-example {
  border-style: solid;
}

border-width: Sets the width of the border.

.border-width-example {
  border-width: 2px;
}

border-color: Sets the colour of the border.

.border-color-example {
  border-color: red;
}

border: Shorthand property for setting all border properties at once.

.border-example {
  border: 2px solid red;
}

border-radius: Sets the radius of the border corners.

.border-radius-example {
  border-radius: 10px;
}

border-top, border-right, border-bottom, border-left: Sets border properties for individual sides.

.border-individual-example {
  border-top: 2px solid blue;
  border-right: 2px solid green;
  border-bottom: 2px solid yellow;
  border-left: 2px solid red;
}

border-spacing: Sets the spacing between cells in a table.

.border-spacing-example {
  border-spacing: 5px;
}

CSS Units

These examples cover various units commonly used in CSS for specifying lengths, sizes, and other dimensions.

/* Pixels (px): A fixed-size unit that represents an absolute length. */
.pixel-example {
  font-size: 16px;
  width: 200px;
  height: 100px;
}

/* Percentages (%): A unit relative to the parent element's size. */
.percentage-example {
  width: 50%;
  height: 50%;
}

/* Viewport Width (vw): A unit relative to the viewport's width. */
.viewport-width-example {
  width: 50vw;
}

/* Viewport Height (vh): A unit relative to the viewport's height. */
.viewport-height-example {
  height: 50vh;
}

/* Em (em): A unit relative to the font-size of the element itself. */
.em-example {
  font-size: 1.2em; /* 1.2 times the parent's font size */
}

/* Rem (rem): A unit relative to the font-size of the root element (html). */
.rem-example {
  font-size: 1.2rem; /* 1.2 times the root's font size */
}

/* Points (pt): A unit commonly used in print media, equivalent to 1/72 of an inch. */
.point-example {
  font-size: 12pt;
}

/* Picas (pc): A unit commonly used in print media, equivalent to 12 points. */
.pica-example {
  font-size: 1pc;
}

/* Inches (in): A unit representing an absolute length in inches. */
.inch-example {
  width: 2in;
}

/* Centimeters (cm): A unit representing an absolute length in centimeters. */
.centimeter-example {
  width: 5cm;
}

/* Millimeters (mm): A unit representing an absolute length in millimeters. */
.millimeter-example {
  width: 50mm;
}

CSS Margins

These examples demonstrate various ways you can apply margins to elements in CSS, including using different combinations of values, auto margins for centering, negative margins, percentage-based margins, and calculations using the calc() function.

/* Margin with a single value: Applies the same margin to all four sides */
.single-margin-example {
  margin: 10px;
}

/* Margin with two values: Applies the first value to the top and bottom margins, and the second value to the left and right margins */
.two-values-margin-example {
  margin: 10px 20px;
}

/* Margin with three values: Applies the first value to the top margin, the second value to the left and right margins, and the third value to the bottom margin */
.three-values-margin-example {
  margin: 10px 20px 30px;
}

/* Margin with four values: Applies the first value to the top margin, the second value to the right margin, the third value to the bottom margin, and the fourth value to the left margin */
.four-values-margin-example {
  margin: 10px 20px 30px 40px;
}

/* Margin with auto value: Automatically adjusts the margin to center the element horizontally within its container */
.auto-margin-example {
  margin: auto;
}

/* Negative margin: Moves the element outside its normal position */
.negative-margin-example {
  margin: -10px;
}

/* Margin using percentage: Sets the margin as a percentage of the containing block's width */
.percentage-margin-example {
  margin: 5%;
}

/* Margin using calc() function: Allows for calculations to determine margin value */
.calc-margin-example {
  margin: calc(50% - 100px);
}

More CSS Functions

These examples demonstrate various CSS functions, including color functions like RGB, RGBA, HSL, and HSLA for defining colors, gradient functions for creating gradients, URL functions for specifying image locations, calc functions for performing calculations, and var functions for defining and using custom properties.

/* RGB Function: Defines a color using red, green, and blue values */
.rgb-color-example {
  color: rgb(255, 0, 0); /* Red color */
}

/* RGBA Function: Defines a color using red, green, blue values, and an alpha channel for transparency */
.rgba-color-example {
  color: rgba(255, 0, 0, 0.5); /* Semi-transparent red color */
}

/* HSL Function: Defines a color using hue, saturation, and lightness */
.hsl-color-example {
  color: hsl(120, 100%, 50%); /* Pure green color */
}

/* HSLA Function: Defines a color using hue, saturation, lightness, and an alpha channel for transparency */
.hsla-color-example {
  color: hsla(120, 100%, 50%, 0.5); /* Semi-transparent green color */
}

/* Linear Gradient Function: Creates a linear gradient as the background */
.linear-gradient-example {
  background: linear-gradient(to right, red, blue); /* Linear gradient from red to blue */
}

/* Radial Gradient Function: Creates a radial gradient as the background */
.radial-gradient-example {
  background: radial-gradient(circle, red, blue); /* Radial gradient from red to blue */
}

/* URL Function: Specifies the location of an image */
.url-example {
  background-image: url('path/to/image.jpg');
}

/* Calc Function: Allows for mathematical calculations to determine property values */
.calc-example {
  width: calc(50% - 20px); /* 50% of the container width minus 20 pixels */
}

/* Var Function: Defines custom properties to reuse values */
:root {
  --main-color: #007bff; /* Define custom property */
}

.var-example {
  color: var(--main-color); /* Use custom property */
}

HTML and CSS – Where to Place CSS Styles in the HTML Web Page

The most common way to include CSS in your web pages is by using external style sheets. This means you can keep all your CSS code in a separate file and simply link it to your HTML document. It’s like having a wardrobe full of stylish outfits that you can mix and match whenever you want! By placing your CSS in an external file, you not only keep your HTML clean and organized, but you also make it easier to maintain and update your styles across multiple pages.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Page Title</title>

    <!-- Link to an external CSS file -->
    <link rel="stylesheet" href="styles.css">

    <!-- You can also include multiple CSS files if needed -->
    <link rel="stylesheet" href="reset.css">
    <link rel="stylesheet" href="responsive.css">

    <!-- Alternatively, you can use a style block to include CSS directly in the HTML file -->
    <style>
        /* Your inline CSS styles go here */
        body {
            font-family: Arial, sans-serif;
        }

        .container {
            width: 80%;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <!-- Your HTML content goes here -->
    <div class="container">
        <h1>Welcome to My Website</h1>
        <p>This is a sample webpage.</p>
    </div>
</body>
</html>

  • The <link> elements are used to link external CSS files (styles.css, reset.css, and responsive.css in this case).
  • You can link as many external CSS files as needed.
  • The <style> block allows you to include inline CSS directly within the HTML file. This can be useful for small amounts of CSS or for styles that are specific to a particular page.

CSS Syntax 

By mastering CSS Syntax, you can unlock endless possibilities to create stunning and captivating websites. The beauty of CSS lies in its simplicity and elegance. With just a few lines of code, you can effortlessly style your web pages and bring your creative vision to life. Imagine the power you hold to align elements, set colours, control spacing, and even create stunning animations!

CSS Syntax empowers you to wield complete control over the appearance and layout of your website, giving your brand a unique and professional edge. So why limit yourself to mediocre designs when you can harness the persuasive power of CSS Syntax to craft visually stunning and user-friendly websites that will leave a lasting impression? Take the plunge, dive into CSS Syntax, and unleash your true creative potential today!

Use CSS Colour

Whether you’re aiming for a sleek and professional look or a bold and adventurous vibe, CSS colour puts the power of persuasion at your fingertips. So why settle for dull and uninspiring designs when you can harness the persuasive power of CSS colour to set your website apart from the competition? Let your imagination run wild, and watch as your digital masterpiece comes alive with the perfect combination of hues. With CSS colour, your website will not only leave a memorable impression but also leave users coming back for more.

Using Named Colours

body {
    background-color: lightblue;
    color: darkgreen;
}

h1 {
    color: crimson;
}

Using Hexadecimal Colours

.container {
    background-color: #3498db;
    color: #ffffff;
}

.button {
    background-color: #2ecc71;
    color: #ffffff;
}

Using RGB Colours

By combining red, green, and blue, you can unleash a whole spectrum of colours to paint your ideas to life. Whether you’re working on graphic design, web development, or even just spicing up a PowerPoint presentation, RGB colour gives you the power to convey emotions and enhance the overall visual appeal. So, don’t be afraid to dive into the world of RGB colour and let your creative spirit shine! Get ready to make your designs pop with this friendly and versatile colour format.

.header {
    background-color: rgb(255, 0, 0); /* Red */
    color: rgb(255, 255, 255); /* White */
}

.footer {
    background-color: rgb(0, 128, 0); /* Green */
    color: rgb(0, 0, 0); /* Black */
}

Using RGBA Colours (with alpha transparency)

.overlay {
    background-color: rgba(0, 0, 0, 0.7); /* Black with 70% transparency */
    color: #ffffff;
}

Using HSL Colours

HSL, which stands for Hue, Saturation, and Lightness, allows you to easily adjust and experiment with colours to achieve the perfect aesthetic. With HSL, you can choose your base hue, tweak the saturation to make it more vivid or muted, and adjust the lightness for a brighter or darker shade. It’s like having a magical colour palette at your disposal! Whether you’re designing a logo, a website, or even creating a piece of art, HSL colour gives you the freedom to unleash your creativity and make your work truly pop.

.accent {
    background-color: hsl(240, 100%, 50%); /* Blue */
    color: hsl(0, 0%, 100%); /* White */
}

Using HSLA Colours (with alpha transparency)

.highlight {
    background-color: hsla(120, 100%, 50%, 0.5); /* Green with 50% transparency */
    color: #ffffff;
}

Why is CSS Essential for Web Design?

Flexibility and Consistency: CSS enables web designers to easily modify the appearance of their websites by making changes in a single CSS file. This ability to separate style from content allows for consistent design elements across multiple web pages, ensuring a seamless user experience.

Enhanced User Experience: With CSS, developers can render web pages that are visually appealing, enhancing readability and user engagement. By controlling the layout, typography, and visual effects, CSS helps create a positive user experience, leading to increased user satisfaction and ultimately, improved conversion rates.

Read moreBasic Web Design: A Beginner’s Guide

Improved Accessibility: CSS empowers web designers to optimize their websites for different devices and screen sizes. Responsive design techniques, achieved through CSS media queries, ensure that the layout and content adapt to different resolutions, making websites accessible on mobile devices and desktops alike.

Efficient Page Loading: CSS files are lightweight, ensuring faster page loading times. When CSS is implemented properly, the browser can swiftly render the website’s layout, resulting in a seamless browsing experience for users. Additionally, by minimizing redundant code, CSS reduces bandwidth usage, which is particularly beneficial for users with slower internet connections.

CSS Selectors and Styling

CSS Selectors: Selectors are one of the fundamental concepts in CSS. They allow designers to target specific HTML elements and apply styles accordingly. There are various types of selectors, such as class selectors, ID selectors, element selectors, and pseudo-classes, each serving different purposes.

Styling Elements and Properties: CSS offers a wide range of styling options, including adjusting fonts, colors, margins, padding, borders, and backgrounds. Additionally, CSS3 introduced advanced styling features like gradients, shadows, transitions, and animations, providing designers with endless creative possibilities.

CSS in Action: Examples

CSS Navigation Menu: CSS can be used to create visually appealing and functional navigation menus. By customizing the look and behavior of navigation links, designers can enhance usability and improve website navigation.

Responsive Web Design: Using CSS media queries, designers can create responsive websites that adapt to different screen sizes and orientations. This ensures that websites maintain optimal functionality and readability across all devices.

CSS Image Galleries: CSS allows designers to style image galleries, creating visually stunning displays. From positioning and transitions to hovering effects, CSS enables a captivating viewing experience for users.

Conclusion

CSS plays a vital role in modern web design, allowing developers to create visually appealing websites with enhanced user experiences. By separating style from content, CSS provides flexibility, consistency, and improved accessibility. Its lightweight nature contributes to efficient page loading times, benefiting both users and search engine rankings. As you continue your journey in web development, mastering CSS will undoubtedly prove to be a valuable asset in creating exceptional websites.

FAQs

Q: What is CSS (Cascading Style Sheets)?

A: CSS (Cascading Style Sheets) is a style sheet language used for describing the presentation of a document written in HTML or XML, including the layout, colors, and fonts. It is specified by the World Wide Web Consortium (W3C) and is a fundamental technology for web development.

Q: How does CSS work with HTML elements?

A: CSS works by associating rules with HTML elements. These rules specify the style applied to the elements, such as color, layout, and font.

Q: What are the key components of CSS?

A: The key components of CSS include the selector, property, and value. The selector is the HTML element to be styled, the property is the aspect of the element to be styled, and the value is the specific style to be applied.

Q: What are the benefits of using CSS?

A: CSS provides a range of benefits, including improved site-wide consistency, better control over layout and design, faster page loading times, and easier site maintenance and updates.

Q: What is the role of CSS in web development?

A: CSS plays a crucial role in web development by separating the content of a document from its presentation. It allows web developers to create engaging and visually appealing websites.

Q: How can I validate my CSS code?

A: You can validate your CSS code using the W3C CSS Validation Service, which checks the syntax and structure of your CSS to ensure it meets industry standards.

Q: What are CSS modules?

A: CSS modules are a set of standardized specifications that define various features and capabilities of CSS, such as layout, color, typography, and more. They provide a modular and organized approach to CSS development.

I am a self-motivated, passionate website designer and developer. I have over ten years’ experience in building websites and have developed a broad skill set including web design, frontend and backend development, and SEO.

Using my growing knowledge base I have built my own company (scriptedart.co.uk) creating websites and ecommerce stores and producing custom graphics and web app functionality for a range of local businesses.

RSS
Follow by Email
Instagram
Scroll to Top