What Is CSS? and How to Use it in Web Design

Have you ever wondered how websites transform from a plain text layout into visually stunning, interactive experiences? The secret lies in CSS, short for Cascading Style Sheets. It’s the styling language of the web, responsible for adding colour, flair, and dynamic design to the basic structure provided by HTML.

What is CSS?

CSS (Cascading Style Sheets) is the cornerstone of web design. It transforms plain HTML structures into visually captivating websites. It’s a language that allows web developers and designers to dictate the appearance of HTML elements. Think of HTML as the skeleton of a webpage, providing the basic content blocks. CSS is the stylish outfit, the makeup, and the overall aesthetic that brings the webpage to life. With CSS, you can control:

  • Colours and Fonts: Change text colour, size, and typeface.
  • Layout: Build multi-column designs, position elements exactly where you want them, and create layouts that seamlessly adapt to any screen size.
  • Backgrounds: Add background images or colours.
  • Animations and Transitions: Create smooth visual effects to enhance user interaction.
  • Add Interactive Touches: Incorporate subtle shadows, smooth transitions, and animations to engage and delight your visitors.

CSS makes websites visually appealing and user-friendly. Its key advantage lies in its separation of content (HTML) from presentation (CSS). This means you can update styles across an entire website with minimal changes to the code.  This efficiency saves time and makes website maintenance a breeze.

CSS used in the W3 Total Cache plugin in WordPress.

CSS Syntax

CSS may look intimidating at first, but its underlying structure is quite straightforward. Let’s break down the key elements:

  • Selectors: Selectors are like special instructions for your browser, telling it which specific HTML elements you want to style. Common types of selectors include Element selectors, Class selectors, and ID selectors.
  • Properties: Think of properties as the different features you want to change about your elements – like colour, font size, background image, and many more.
  • Values: Values are the specific adjustments you want to make to a property. For instance, you could set the colour property to red or the font-size property to 16px.
  • Declarations: A declaration is a single instruction for your browser. It combines a property with its chosen value, separated by a colon and ending with a semicolon.
  • Style Rules: A style rule groups all your declarations for a specific selector within curly brackets {}. It tells the browser which elements to style and how to style them.
Where to Put Your CSS

There are three main places to include CSS in your website:

  • Inline Styles: You can add style attributes directly within your HTML tags, but this method is the least recommended as it makes your code harder to maintain.
  • Internal Stylesheet:  You can place <style> tags within the <head> section of your HTML document, defining styles specifically for that page.
  • External Stylesheet: The most common and organized method is to create a separate file with a .css extension. Then, you link that file to your HTML using a <link> tag within the <head> section.
The Cascade and Specificity

Have you ever wondered how the browser decides which CSS style to apply when there are multiple conflicting rules for the same element? This is where the ‘Cascade’ and ‘Specificity’ come into play.

The Cascade

Think of the cascade as a waterfall of style rules. Browsers generally follow these principles:

  • Order of Stylesheets: If rules in different stylesheets have the same specificity, the last one loaded takes precedence.
  • Source Order within a Stylesheet: Within the same stylesheet, if multiple rules apply with equal specificity, the last one defined in the code wins.
  • Inline Styles: Inline styles (defined directly in an element’s style attribute) have the highest priority, often overriding other styles.

Specificity is like a scoring system that helps the browser determine which rule is most important. More specific selectors generally override less specific ones. Here’s a basic hierarchy:

  • Inline styles (highest specificity)
  • ID selectors
  • Class selectors, attribute selectors, and pseudo-classes
  • Element selectors (lowest specificity)

Important Note: You can use the important declaration to override almost any other style rule, but use this sparingly, as it can make your CSS harder to manage

Understanding Inheritance

Child elements inherit some CSS properties from their parent elements. For example, you set a font colour on the <body> tag. In that case, all text elements within the body will generally inherit that colour unless they have a different colour explicitly defined. However, properties like margins, padding, and borders are not inherited.

The Box Model

Imagine every element on your website as a little box.  The CSS Box Model describes the different layers that make up these boxes, which is crucial for understanding how they are sized and spaced on the page. Here’s the breakdown:

  • Content:  This is the core of your element – the actual text, image, or other media you want to display.
  • Padding: This is the transparent area surrounding the content. Think of it as the cushioning inside the box. The padding adds breathing room between the content and the border.
  • Border: This is the visible line (if you choose to have one) that goes around the padding and content. You can control the border’s style (solid, dotted, dashed, etc.), thickness, and colour.
  • Margin: The transparent space outside the border creates separation between your element and its neighbours. Margins are key to creating clean layouts and preventing elements from bumping up against each other.
Controlling Element Dimensions (Width and Height)

The width and height properties set the size of your box’s content area. Remember that padding, border, and margin will add to the element’s overall space on the page.

Box-Sizing: border-box

The default box-sizing behaviour can be a bit counterintuitive. With content-box (the default), if you set a width of 200px, add 20px of padding, and a 5px border, the total width of your element becomes 250px. The border-box value for the box-sizing property changes this behaviour. With the border box, the padding and border are included within the total width/height you set. This makes calculating dimensions much more intuitive and is often a preferred approach.

Layout and Positioning
Display Properties

The display property is fundamental in controlling how elements are laid out on your website. Here are the most common values and what they do:

  • Block: Block-level elements take up the full width available, always start on a new line, and can have height and width set. Examples: <div>, <h1> – <h6>, <p>, <header>, <footer>
  • Inline: Inline elements only occupy the space needed for their content. They sit within a line of text, cannot have a width or height set, and are affected by line height. Examples: <span>, <a>, <img>
  • inline-block: This is a hybrid, allowing you to set the width and height of an element that still flows within a line of text. Think of images with captions aligned side-by-side.
  • None: The element is completely hidden and removed from the page’s flow. It will only take up a little space.

CSS lets you precisely control the position of elements, breaking them out of the normal document flow if needed.  Here are the key positioning properties:

  • Static: The default behaviour. Elements are positioned according to their place in the HTML document.
  • Relative:  The element is positioned relative to its normal position in the flow.  It acts as a reference point for any child elements you position with ‘absolute’ (more on that later).
  • Absolute: The element is removed from the normal document flow and positioned about its nearest positioned ancestor (or the browser window if none exists). Absolute positioned elements can overlap other content.
  • Fixed: The element is removed from the flow and stays in a fixed position on the screen, usually relative to the browser window. It doesn’t move even when you scroll. Great for elements like sticky headers.
  • Sticky:  A hybrid behaviour. The element acts like it’s relatively positioned until it reaches a certain scroll position, then becomes fixed.

When elements overlap, the z-index property determines the stacking order. Think of it like layers of paper – elements with a higher z-index appear on top of those with a lower z-index. This only applies to positioned elements (relative, absolute, fixed, or sticky).

Floats and Clearing

While less commonly used for primary layout these days, understanding floats is still valuable as you might encounter them on older websites or for specific use cases.

  • The Float Property: The float property (with values like left, right, and none) removes an element from the normal document flow and pushes it to the specified side. Other content can then wrap around it.
  • Clearing Floats: A floated element’s parent container often collapses in height because floats are removed from the flow.  The clear property (with values like both left and right)  is used on elements after a floated element to prevent this collapsing behaviour and ensure the parent has the correct height. A common technique for clearing floats is the “clear fix”.
Why Floats Have Largely Been Replaced

Floats can be tricky to manage, especially for complex layouts.  More modern CSS techniques like Flexbox and CSS Grid have emerged, offering greater flexibility and control for building robust layouts.


Flexbox (short for Flexible Box Layout) is a CSS module designed to simplify the creation of flexible, responsive layouts. It gives you extraordinary control over the distribution and alignment of elements, even if their content size is unknown or dynamic.

Key Concepts
  1. Flex Container: An element with display: flex becomes a flex container. Its direct children become flex items.
  2. Main Axis:  The primary direction along which flex items are laid out. It’s set by flex-direction and can be: row (default), row-reverse column, or column-reverse.
  3. Cross Axis: The axis perpendicular to the main axis. Think of it as the opposite direction of the main axis.
  4. Flex Properties: These properties control how flex items behave within the container. 
CSS Grid

CSS Grid is a two-dimensional layout system designed specifically for creating complex, grid-based structures.  It gives you fine-grained control over both rows and columns, making it ideal for building magazine-style layouts, dashboards, and more.

Key Concepts
  1. Grid Container: An element with display: grid becomes a grid container, and its direct children become grid items.
  2. Grid Tracks:  Grid lines define the structure of the grid. The spaces between grid lines are called tracks – these can be rows or columns.
Flexibility and Power

CSS Grid allows you to position grid items using line numbers or names precisely, span multiple rows or columns, and create responsive grids that adapt to various screen sizes. Its unique capabilities make it perfect for designs that break away from simple columnar structures

Design and Visual Styling

Colours and Backgrounds

Colours can dramatically change the mood and atmosphere of your website. Let’s explore how CSS lets you work with them:

Color Formats
  • Hexadecimal Values: 6-digit codes representing Red, Green, and Blue values (e.g., #FF0000 is pure red).
  • RGB: Values for Red, Green, and Blue on a scale of 0-255 (e.g., RGB (255, 0, 0) is pure red).
  • RGBA: Adds an alpha channel for transparency (e.g., RGBA (255, 0, 0, 0.5) is a semi-transparent red).
  • HSL: Hue, Saturation, and Lightness – a more intuitive way to define colours (e.g., HSL (0, 100%, 50%) is also pure red).
  • Background Colors:  Use the background-colour property to add colours behind elements.
  • Background Images: Use the background-image property to set backgrounds and customize how they’re positioned (background-position), repeated (background-repeat), and more.
  • Gradients: Create smooth transitions between colours. CSS supports linear gradients (linear-gradient) and radial gradients (radial-gradient)  for eye-catching effects.

Typography significantly influences your website’s readability and overall aesthetic. CSS gives you extensive control over your text styling:

Font Properties:
  • font-family: Specifies the font or a list of fallback fonts.
  • font-size: Sets the size of your text.
  • font-weight: Controls the boldness of your text (e.g., bold, normal, or numeric values like 400, 700).
  • font-style: Makes text italic or oblique.
Line-height, Letter-spacing, and More:
  • Line height: Controls the space between lines of text for better readability.
  • Letter spacing: Adjusts spacing between letters.
  • word-spacing: Adjusts spacing between words.
  • text-align: Align your text (left, right, centre, or justify).
  • text-decoration: Adds underlines, overlines, strikethroughs, etc.
  • text-transform: Controls capitalization (uppercase, lowercase, etc.).
Web Fonts

Go beyond basic system fonts! Web fonts services like Google Fonts provide a vast library of beautiful typefaces. You can easily integrate these into your website using CSS.

Margins and Padding

Recall that margins create space outside an element’s border, while padding creates space inside the border.  Use these properties to control the spacing between elements and create a visual hierarchy.

Units of Measurement
  • Pixels (px): Fixed unit, offers precise control but might not scale well across different screens.
  • em: Relative to the current font size, it is useful for creating scalable designs.
  • rem: Relative to the root element (usually <html>) font size.
  • Percentages (%): Sizes elements relative to their parent container. Great for responsive layouts.
  • Viewport Units (vw, vh): Relative to the browser viewport size (e.g., 100vw means 100% of the viewport width).

The overflow property controls what happens when the content exceeds an element’s dimensions.  Possible values include:

  • visible (default): Content spills outside the box.
  • hidden: Content is clipped, and anything outside the box is hidden.
  • Scroll: Adds scrollbars so users can view all the content.
  • auto: Adds scrollbars only if content overflows.
Controlling Element Dimensions

Remember width and height properties set the dimensions of the content area.  You can also use:

  • max-width and min-width for setting size ranges
  • max-height and min-height to set limits on height

Visual Effects

Box Shadows
  • The box-shadow property adds realistic or stylized shadows to your elements.  Customize the shadow’s offset, blur radius, spread, and colour to achieve the desired effect.
Text Shadows
  • Similar to box shadows, the text-shadow property adds a touch of dimensionality to your text.  Control the offset, blur, and colour for subtle or dramatic effects.


CSS filters offer a way to manipulate an element’s appearance visually.  Common filters include:

  • blur(): Adds a Gaussian blur.
  • grayscale(): Converts the element to grayscale.
  • sepia(): Applies a sepia tone for a vintage look.
Transitions and Animations

Want to make your website feel more interactive? Let’s touch on the basics of CSS transitions and animations:

  • The transition property allows you to smoothly change property values over a specified duration. For example, you could create a hover effect in which an element’s background colour gradually changes.
  • The animation property and @keyframes rule give you more fine-grained control over creating custom animations.  With CSS animations, you can move elements, change their scale, rotate them, and much more.

Responsive Design with CSS

The Importance of Responsiveness

With people browsing the web on smartphones, tablets, laptops, and large desktop monitors, your website must provide an optimal experience on all screen sizes.  Responsive design ensures that your content is rearranged and resized gracefully to fit any device.

Media Queries

The heart of responsive design in CSS lies in media queries. Think of them as special rules that allow you to apply different styles depending on the screen size, orientation, and other features of the user’s device.

Basic Media Query Concepts

A media query typically specifies a minimum or maximum screen width (or a range between the two). If the device’s screen size matches the condition, CSS rules within that media query will be applied.

Breakpoints:  Media queries often target common breakpoints – widths where the layout might need significant changes to look good.  Some popular breakpoints roughly correspond to device categories (e.g., 768px for tablets and 1024px for laptops).

Key Strategies Using Media Queries
  • Mobile-First:  Start by designing your website for smaller screens, and then use media queries to add styles that enhance the layout for larger screens.
  • Fluid Layouts:  Use flexible units (like percentages) alongside techniques like Flexbox and Grid to create layouts that naturally adapt to different screen sizes.
  • Responsive Images: Ensure your images scale well for different devices. This helps optimize page loading times, especially on smaller screens.
  • Typography Adjustments:  Use media queries to adjust font sizes and line heights to maintain readability across different devices.
  • Navigation Adaptations:  Consider how your navigation will change between a horizontal navigation bar on desktops and a “hamburger” menu on mobile screens
Thorough Testing

Always test your responsive design on a range of physical devices if possible.  If you don’t have many devices, you can use device emulators in your browser’s developer tools to simulate different screen sizes.

Preprocessors (Sass, Less)

Preprocessors add power and flexibility to your CSS code. Let’s briefly introduce the benefits of popular options like Sass and Less:

  • Variables: Define reusable values for colours, fonts, etc.
  • Nesting: Write CSS with a clearer hierarchy, improving organization.
  • Mixins: Create reusable blocks of CSS code.
  • Functions: Perform calculations within your stylesheets.
CSS Specificity Tips

Understanding specificity rules is essential when dealing with complex stylesheets.  Here are some tips for managing those occasionally tricky situations:

  • Avoid Overly Specific Selectors: Using long chains of selectors can make overriding styles harder.
  • Strategic Use of! important: While generally used sparingly, the! important declaration can be helpful when you need to override styles in specific situations.
  • Specificity Calculator: Online tools can help you calculate and compare selector specificity.
Browser Compatibility and Debugging
  • Cross-Browser Testing: Test your website in different browsers (Chrome, Safari, Firefox, Edge) and their various versions, as they can have subtle rendering differences.
  • Vendor Prefixes:  While less common these days, occasionally, you may need to include vendor-specific prefixes (-webkit-, -Moz-, etc.) for certain properties to support older browsers.
  • Browser Developer Tools:  Become best friends with your browser’s developer tools. They allow you to inspect elements, see which styles are applied, debug layouts, and much more.
Performance Optimization
  • Minimize CSS File Size:   Use minification tools to remove unnecessary whitespace and comments, reduce file size, and speed up loading times.
  • Efficient Selectors:  Aim for selectors that the browser can match quickly.  Overly complex selectors can slow down rendering.
  • Hardware Acceleration:  Leverage CSS properties like transform and opacity for animations, as they can often be offloaded to the GPU for smoother performance.
Accessibility in CSS

Designing with accessibility in mind ensures your website is usable by everyone, including those with disabilities.  Here are a few CSS considerations:

  • Focus States: Provide clear visual indicators when using: focus for keyboard navigation.
  • Colour Contrast: Ensure sufficient contrast between text and backgrounds for readability.
  • Semantic HTML: Use headings, lists, and other HTML tags appropriately for structure, as this aids screen readers.
  • ARIA Attributes: Use ARIA attributes where necessary to provide additional context for assistive technologies.

Throughout this comprehensive guide, you have journeyed through the fundamentals of CSS, layout techniques, visual styling, responsive design, and best practices. Understanding CSS gives you the power to customize your website’s appearance precisely to your liking.

Scroll to Top