Home/Blog/Web Development/CSS Tricks to Become a Web Magician
Home/Blog/Web Development/CSS Tricks to Become a Web Magician

CSS Tricks to Become a Web Magician

14 min read
Mar 03, 2025
content
Understanding CSS units
Absolute units
Relative units
Understanding the CSS box model
The box-sizing property
Explanation
Why use .box-border?
CSS positioning techniques
The position property
Explanation
Flexbox and CSS Grid
Flexbox for layouts
CSS Grid for layouts
Theming with CSS variables and SCSS
CSS variables
Explanation:
Theming with SCSS
Explanation
Media queries and responsive web design
Breakpoints in media queries
Common media query features
Animations in CSS
Basics of CSS animations
Explanation
Animation properties
Explanation:
Conclusion

Key takeaways:

  • It is crucial to understand both absolute and relative units for creating flexible and responsive designs.

  • Understanding the CSS box model, especially the box-sizing property, is essential for accurate layout management. Using border-box can simplify responsive designs by ensuring that the element’s total width and height include the padding and borders.

  • Advanced positioning techniques, including Flexbox and CSS Grid, offer powerful ways to efficiently create complex and responsive layouts. These modern layout systems often replace older methods like floats and tables.

  • CSS variables, combined with preprocessors like SCSS, enable the creation of consistent and easily manageable themes across web projects.

  • Media queries ensure your website adapts to different screen sizes, resulting in a responsive design that ensures optimal user experience across all devices.

  • CSS animations add interactivity and visual appeal to web pages. By leveraging keyframes and animation properties, you can create engaging effects that enhance user experience without compromising performance.

CSS (Cascading Style Sheets) is the core building block of web development, providing the means to control the presentation of HTML elements on the web page. Did you know that with just a few lines of CSS, you can make your website adapt seamlessly to every device size or add animations that guide user attention like a magician’s wand? It’s truly a powerful tool that can convert ordinary web pages into visually and highly interactive user experiences. It does not matter if you’re a seasoned developer looking to refine your CSS skills or a newcomer eager to learn the concepts of front-end design. While many developers are familiar with basic CSS properties like color, font-size, and margin, CSS offers a number of advanced features that can significantly enhance the functionality of web pages.

In this blog, we’ll explore some of the advanced CSS functionalities, offering in-depth explanations and practical examples to help you understand the full potential of CSS and how they can be used to create clever, efficient web design. We’ll start with the fundamentals of units and the box model to the intricacies of responsive design and animations. By the end of this blog, you’ll be equipped with the knowledge and techniques to craft clever, efficient, and mesmerizing web designs.

The Complete Advanced Guide to CSS

Cover
The Complete Advanced Guide to CSS

My Goal is to take you from a beginner (or intermediate) CSS user to becoming one of the best CSS devs you know! 👉🏻 COURSE CONTENT? 1. A detailed look at CSS Fundamentals 2. Practical SVG for today 3. A Sane Guide to Responsive Design 4. Creating sleek Interfaces with CSS Animations and Transitions 5. Writing Maintainable CSS and tips for CSS at Scale 6. Learn the CSS Grid by Building ... wait for it! 😉 7. Get a Private slack Invite where you can ask me anything 8. Gain a Solid Understanding of CSS Fundamentals 9. Build Practical Projects 10. Flexbox, Variables, Gradients, Backgrounds, Responsive Images, Handy pro tools, and many more! 👉🏻 WHAT ARE THE REQUIREMENTS? The course assumes no previous knowledge of CSS 👉🏻 WHAT'S THE TARGET AUDIENCE? 1. Backend Engineers looking to level up their frontend design skills 2. Budding developers looking to create beautiful applications 3. Generally, engineers who want to stand out by truly understanding the internals of CSS Ready to upgrade?

10hrs
Beginner
131 Playgrounds
159 Illustrations

Understanding CSS units#

Understanding CSS units is fundamental to creating flexible and responsive designs. CSS offers a variety of units to define sizes, from absolute measurements to relative scales, each serving different purposes depending on the context.

Absolute units#

Absolute units represent fixed measurements that do not change relative to other elements or viewport sizes. They are useful when precise control over an element’s size is required, regardless of the device or screen size.

  • Millimeters (mm)

  • Centimeters (cm)

  • Inches (in)

  • Pixels (px)

  • Points (pt)

  • Picas (pc)

An example of using absolute units is given below:

Relative units#

Relative units adapt based on other properties, making them ideal for responsive design. They offer flexibility and ensure that elements scale appropriately across different devices and screen sizes.

  • %: Relative to the parent element’s size.

  • em: Relative to the element’s font size.

  • rem: Relative to the root (<html>) element’s font size.

  • vw: Relative to 1% of the viewport’s width.

  • vh: Relative to 1% of the viewport’s height.

  • vmin: 1% of the viewport’s smaller dimension.

  • vmax: 1% of the viewport’s larger dimension.

Note: The viewport is the dimension of the screen where the web page is displayed.

An example of using relative units is given below:

Understanding the CSS box model#

The CSS box model is a core concept of CSS and web page styling. It defines how the elements render and interact with each other on a web page. It comprises four main components: content, padding, border, and margin.

  1. Content: It is the innermost part of the box that contains the actual content (text, images, etc.). It is controlled by properties like width and height.

  2. Padding: It is the space between the content and the border.

  3. Border: This is the edge of the box around the content and padding.

  4. Margin: This is the outermost layer that creates space outside the element, separating it from neighboring elements.

It’s important to understand how these components interact to have precise layout control and design consistency.

CSS box model’s overview
CSS box model’s overview

By default, width and height apply only to the content area. The total size of an element includes the content (width and height), padding, and the border. Therefore, to calculate the total size of an element, we can use something like the following:

Total width = content width + padding-left + padding-right + border-left + border-right
Total height = content height + padding-top + padding-bottom + border-top + border-bottom
Calculation of the total size of an element

The box-sizing property#

It alters the default calculation of an element’s total width and height. There are two values that can define this property:

  • .box-content: This is the default value. Only the content contributes to the width and height of an element. Padding and borders are added outside the content area, increasing the total size of the element.

  • .box-border: Content, padding, and border contribute to the width and height of the element. This makes it easier to manage element sizes without unexpected overflows.

Consider the following example:

Explanation#

  • Line 6: With .box-content, the total width becomes 200px (content) + 30px (left and right padding) + 10px (left and right border) = 240px.

  • Line 14: With .box-border, the total width remains 200px, with the content area adjusted to accommodate padding and border.

Why use .box-border?#

  • It simplifies layout calculations, especially when dealing with percentage-based widths and padding, keeping element sizes consistent.

  • It prevents layout issues caused by padding and border additions.

  • It enhances maintainability by reducing the need for complex calculations.

  • It allows you to create responsive grid-based layouts that adapt to various screen sizes.

If you’re interested in creating a fully functional microblogging platform with search and admin features, explore this project, “Build a Microblogging App Using PHP, HTML, JavaScript, and CSS,” to learn how to style the application using CSS.

CSS positioning techniques#

Positioning elements accurately is key to creating sophisticated and responsive layouts. CSS provides several positioning methods, each with unique capabilities and use cases.

The position property#

The position property defines how an element is positioned on a page. It can be set to different values, and understanding each value allows for precise control over element placement.

  • static: This is the default positioning. Elements flow naturally on the page without any positioning.

  • relative: The element is positioned relative to its normal position. Adjustments using top, right, bottom, and left move the element from its original spot.

  • absolute: The element is positioned relative to the nearest positioned ancestor. Removed from the normal flow, allowing for precise placement.

  • fixed: This is positioned relative to the viewport. Remains in place even when the page is scrolled.

  • sticky: It is a combination of relative and fixed positioning. The element acts as relative until it crosses a specified threshold and becomes fixed.

Explanation#

  • Lines 10–15: The .relative-box class shifts the element 10px down and 20px to the right from its original position without affecting other elements.

  • Lines 24–29: The .absolute-box class positions the element 20px from the top and 20px from the right relative to its nearest positioned ancestor (.absolute-container).

  • Lines 31–36: The .fixed-box class ensures that the element remains fixed at the bottom-right corner of the viewport, staying in place even when the page is scrolled.

  • Lines 38–42: The .sticky-box class sticks to the top of the viewport when scrolled past its initial position, providing persistent visibility.

Flexbox and CSS Grid#

While traditional positioning methods are powerful, modern layout systems like Flexbox and CSS Grid offer more intuitive and flexible ways to design complex layouts. We will understand each of them in detail below.

Flexbox for layouts#

Flexbox is ideal for one-dimensional layouts, allowing for the alignment and distribution of space among items in a container. It simplifies tasks like centering elements, creating navigation bars, and building responsive components. It has two major components: flex container and flex items.

Components of a flexbox
Components of a flexbox

Let’s look at an example of using Flexbox to create a simple navigation menu:

Flexboxes are responsive in nature. They adjust the layout dynamically based on the container’s size. Flexboxes allow us to easily center elements both vertically and horizontally.

CSS Grid for layouts#

CSS Grid is mostly used for two-dimensional layouts. It allows you to create a grid-based layout with rows and columns. It’s a powerful system for creating complex and responsive layouts with ease. It places items in specific grid cells and allows you to control the size of rows and columns independently. These can generally be used for complex page layouts, including dashboards, galleries, and multi-column designs.

CSS Grid layout
CSS Grid layout

Let’s look at an example of using CSS Grid to create a simple layout:

Often, combining both Flexbox and CSS Grid can lead to more efficient and manageable layouts. You should consider using CSS Grid for the overall page structure and Flexbox for internal component alignment.

Theming with CSS variables and SCSS#

Web app creation requires intense attention to user experience and brand presentation (personal or professional). A sleek design is nothing without consistency, but we can use CSS to efficiently paint our web apps with an aesthetic theme.

Note: When building large stylesheets with extensive variables, it is recommended that we code in SCSS or SASS instead of pure CSS.

CSS variables, also known as custom properties, are essential for establishing a theme. More specifically, CSS variables are inherited. Inheritance means we can attribute some variables to certain sections of our app and even override them in child components if necessary.

SCSS is a CSS preprocessor that extends CSS with features like variables, nesting, mixins, and more, making stylesheets more maintainable and scalable.

CSS variables#

CSS variables allow you to define reusable values that can be dynamically updated throughout your stylesheet. They provide a way to manage colors, fonts, spacing, and other design tokens, enabling easy theme switching and customization.

Let’s look at a simple example of defining and using CSS variables:

Explanation:#

  • :root: The root pseudo-class targets the highest level of the HTML document, making variables accessible throughout the entire stylesheet.

  • var(--variable-name): This retrieves the value of a CSS variable.

Theming with SCSS#

SCSS (Sassy CSS) provides advanced features like variables, nesting, mixins, and functions, making it highly useful for managing large and complex themes. SCSS variables work similarly to CSS variables but are precompiled, meaning they are resolved at build time, not runtime.

// Define theme variables
$primary-color: #3498db;
$secondary-color: #2ecc71;
$font-family: 'Arial, sans-serif';
$padding: 10px;
// Create reusable mixin for buttons
@mixin button-style($bg-color, $text-color) {
background-color: $bg-color;
color: $text-color;
padding: $padding;
border: none;
border-radius: 5px;
}
// Use variables and mixins in styles
body {
background-color: $primary-color;
color: white;
font-family: $font-family;
padding: $padding;
}
button {
@include button-style($secondary-color, white);
}
Theming with SCSS

Explanation#

  • Lines 2–5: We first define theme variables as central definitions for theme properties (e.g., colors, typography, spacing).

  • Lines 8–14: We create a reusable mixin—a reusable block of CSS code that takes parameters ($bg-color, $text-color) for flexibility. The mixin reduces repetition by allowing you to apply the same styles to multiple elements with slight variations.

  • Lines 17–22: The document body inherits global theme styles, such as background color, font family, and padding, ensuring consistency across the application.

  • Lines 24–26: We style the buttons in the HTML document. The button-style mixin is applied with specific parameters:

    • Background color: $secondary-color.

    • Text color: white.

Looking to design a personalized digital resume? Try this project, “Creating an Online CV with HTML and CSS,” to learn how to craft an interactive online CV using HTML and CSS for a polished and unique presentation.

Media queries and responsive web design#

Responsive web design (RWD) is essential to modern web design. The practice of RWD instructs pages to intelligently scale their layouts based on the screen size they are being displayed on. Media queries are a core feature of RWD, allowing you to apply CSS styles conditionally based on device characteristics.

A media query is a feature of modern web development that allows web pages to fluidly restructure their layouts based on the screen size of the device displaying the page. A media query uses a test expression to apply specific styles only when the conditions in the query are met. For example, you can adjust font sizes for small screens or switch to a multi-column layout on larger screens.

A basic media query syntax would look something like this:

@media (condition) {
/* CSS rules */
}
Basic syntax of a media query

A working example is below, where the media query applies the enclosed styles when the viewport width is at least 480 pixels. The background color changes from lightblue to lightgreen when the viewport width exceeds 480px.

Breakpoints in media queries#

Breakpoints are specific widths (or other conditions) at which your design adjusts to better fit the screen. Typical breakpoints for responsive web design include:

  • Small devices (mobile): max-width: 480px

  • Medium devices (tablets): max-width: 768px

  • Large devices (desktops): min-width: 1024px

These breakpoints ensure your site looks great on a range of devices.

Common media query features#

Media queries can target a variety of device features, enabling precise control over when and how styles are applied. Below is a table of common media query features. Most can be implemented with min- and max- prefixes to set ranges that test for requirements.

1. Dimensions: This category covers features related to the size of the viewport and its constraints.

Feature

Description

width

Width of the rendering surface.

height

Height of the rendering surface.

min-width / max-width

Minimum and maximum width of the rendering surface.

min-height / max-height

Minimum and maximum height of the rendering surface.

2. Display properties: This category includes features about how the display presents content, such as resolution, aspect ratio, and orientation.

Feature

Description

resolution

Resolution of the output device specified in dpi or dpcm.

aspect-ratio

Aspect ratio of the viewport.

orientation

Whether the device is in portrait or landscape mode.

3. User preferences: These features adapt based on user-specific preferences for content presentation.

Feature

Description

prefers-color-scheme

User’s preferred color scheme (light or dark).

4. Color and display type: These features define the device’s color or display capabilities, such as color support and monochrome displays.

Feature

Description

monochrome

Represents the number of bits per pixel in a monochrome frame buffer (integer).

Animations in CSS#

Animations are some of CSS’s most eye-catching aspects. You may think of these as pop-ups or notifications that bounce to attract attention, but clever animations can aid the user experience and even a website’s functionality. CSS animations are optimized by browsers for smooth performance, and their simple syntax makes it easy to define and apply animations.

Basics of CSS animations#

CSS animations are defined using the @keyframes rule, which specifies the intermediate steps of an animation sequence. These animations are then applied to elements using various animation properties.

Consider the simple example below, where the element with the “Hello World” text fades on the page using CSS animation.

Explanation#

  • Lines 1–4: The @keyframes fadeIn defines the animation sequence from 0% opacity to 100% opacity.

  • Lines 6–22: The .fade-in-element class applies the fadeIn animation over 2 seconds with an ease-in timing function. The forwards fill mode ensures the element retains the final state after the animation completes.

Animation properties#

Some of the main animation properties provided by CSS are as follows:

  • animation-name: Specifies the name of the animation defined using @keyframes.

  • animation-duration: Defines how long the animation will take to complete one cycle. The default for this value is 0, so if it is left unchanged, then the animation will not occur.

  • animation-timing-function: Defines the speed curve of the animation. It can have the following values:

    • linear: Same speed from start to finish.

    • ease: Slow beginning, fast middle, and then slow end.

    • ease-in: Slow beginning.

    • ease-out: Slow end.

  • animation-delay: Creates a delay for the beginning of the animation.

  • animation-iteration-count: Specifies the number of times the animation will run.

  • animation-direction: Specifies whether the animation plays forward, backward, or alternates between directions. It can have the following values:

    • normal: Plays forwards (default).

    • reverse: Plays backward.

    • alternate: Alternates between forward and backward.

    • alternate-reverse: Alternates starting in reverse.

  • animation-fill-mode: Defines the style of a target element when the animation is not playing. This property ensures that animations do not alter an element until we play the first keyframe. It can have the following values:

    • none: Animation will not apply styles until executed.

    • forwards: Element will retain style values set by the last keyframe.

    • backwards: Element will receive the style values set by the first keyframe.

    • both: The animation properties will follow the rules for both forward and backward.

Below is a slightly complex animation using some of the properties defined above.

Explanation:#

  • Lines 1–5: The @keyframes bounce defines a bounce effect by translating the element along the Y-axis at specific keyframes.

  • Lines 7–21: The .fade-in-element class applies the bounce animation with a 2-second duration and infinite iterations.

Conclusion#

Mastering CSS takes a long and concerted effort, and there is plenty more to learn than just a few topics in this blog. Becoming proficient in advanced CSS techniques allows you to build sophisticated and responsive web designs that stand out. Whether you’re building intricate layouts, implementing dynamic themes, or adding engaging animations, the skills you’ve acquired through this blog will be a strong foundation for your web development journey. Start experimenting with these tricks and watch your web designs transform.

Practice CSS styles with a library by completing this project: Build an Online Video Player Using Angular and Tailwind CSS, where we build an online video player application using Videogular and Angular.

Frequently Asked Questions

What is the difference between em and rem units?

em: Relative to the font size of the element it’s used on. This means that if you set an element’s font size to 2em, it will be twice the size of its parent element’s font size.

rem: Relative to the font size of the root (<html>) element. This provides more consistency across the project since it’s based on a single reference point.

How do I choose between Flexbox and CSS Grid?

Can CSS variables be used without preprocessors like SCSS?


Written By:
Hamna Waseem
Join 2.5 million developers at
Explore the catalog

Free Resources