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

13 min read
Aug 31, 2022

This article will take a look at some of the specific functionalities of CSS and how they can be used to create clever, efficient web design. While we have some great blogs on CSS, this will be less beginner-centric than a CSS basics tutorial and more varied than a CSS selector cheat sheet. If you want to dive a little deeper into the nuances of CSS a basic understanding of preliminary CSS is a solid prerequisite, but by no means required. We’ll go a bit beyond simple selectors and syntax.

We’ll focus on some of the underrepresented areas of CSS and how they can be used as a tool for creative and flashy web design. CSS is capable of much more than coloring text and a few bouncing animations. We’ll start with a couple functional features that make your webpages smarter and more responsive like CSS’s range of relative units, the block model, and positioning. From there we’ll move on to elements of responsive web design, a theming solution, and animations.

We’ll cover:


Get hands on with CSS today.#

Try one of our 400+ courses and learning paths: The Complete Advanced Guide to CSS.

CSS is an essential language for front-end development. It is strong, straightforward, and expressive when it comes to establishing a user interface. HTML informs the content of a web page, but CSS enables us to shape, restructure and breathe life into it.

While CSS is a core building block of any front-end developer’s arsenal, it can often get overlooked when it comes to the flashy, new front-end technologies that web developers often get to play with. When it comes to magic, CSS has a couple tricks up its sleeves, and we aim to help you along your journey to becoming a regular web wizard.

CSS magic could be any number of quirks and features of the language.

We’re going to go a bit further than just a couple tips and tricks though. We’ll explain several unique and effective ways to add functionality and flexibility to everything from your single-page applications to more involved web projects. There is an enormous well of CSS knowledge online; this is just a small sliver of what is possible.

First, a refresher on units. CSS features many different units that can be used to describe design parameters. While not necessarily magical in their own right– certain units can be used to create relative dependencies among design elements.

Basic CSS units are those that describe absolute lengths. These are units of exact measurement and will not change even on different devices

  • millimeters (mm)
  • centimeters (cm)
  • inches (in)
  • pixels (px)

While these are handy for being precise and deliberate in your measurements of layouts and web page elements, we need something with a little more flexibility. We can turn to relative lengths to rectify this. Relative lengths rely on percentages or fractions of other values in order to scale certain elements appropriately. Some of these lengths are:

  • %, relative to a parent element
  • em, relative to the font-size of the element
  • rem, relative to the font-size of the root element
  • vmin, relative to 1% of the viewport’s smaller dimension
  • vmax, relative to 1% of the viewport’s larger dimension

The viewport is the dimension of the screen that the webpage is being displayed on.

Below is an interactive widget to allow you to experiment with different units.

  • HTML
  • CSS (SCSS)
html
css

The block model refers to CSS’s default instructions for a website layout to render each element in a rectangular box. Each block is composed of the four areas pictured below: content, padding, border, and margin.

widget

Typically, the padding, border, and margin areas are all invisible. This can cause complications when meshing boxes neatly into a compact web page, or when trying to contain boxes within others.

The power of the block model lies in the ability to use multiple units when assigning dimension values. box-sizing is a property that can constrain content boxes based on the parameters of their parent containers. There are two values that can define this property:

  • content-box: the default value. The padding and border are added on to the content box
  • border-box: the padding and border are incorporated and can be sized deliberately.
  • HTML
  • CSS (SCSS)
html
css

Border-box#

The magical part of all this is that border-box allows us to set certain values for the block while still facilitating percentage-based scaling. Instead of manually resizing the padding area of a box for each default box we can mixed-unit to set the border and padding dimensions without running into sizing edge cases.

Border-box#

  • HTML
  • CSS (SCSS)
html
css

In the above example, we are able to simplify the relationship between width and padding with the border-box sizing. Even by setting padding to an absolute length in pixels, we can control the amount of space the element takes up on the layout with width as a percentage value. This can be done for every element on a web page.

We can use any valid absolute or relative length to specify padding and a percentage value for width using border-box.


Positioning#

The term ‘layout’ generally refers to the structure of a web page and how it displays its content. Layouts in CSS describe certain properties of web page content. These values belong to the display property.

The flexbox model simplifies syntax for layouts by removing the need for floats or table display workarounds.

In CSS, layouts refer to the positioning of multiple boxes, like the ones mentioned in the previous section. The act of placing these boxes around the web page is called positioning. An element can be positioned by referring to the top, bottom, left, and right edges of a page or parent element.

widget

Above is an example of relative positioning. There are two main elements: a green div and a blue div. Inside the blue div is a child element to be positioned. We can use the top, bottom, left, and right values as a metric to do this.

In CSS, elements have a position property that can be set to several different values. These values are:

  • static: a value used to describe an unpositioned element
  • relative: creates a reference point for any child elements contained within
  • absolute: the element will be moved to the appropriate position relative to the parent element

In CSS, any element that does not have the value position: static is considered positioned.

Take the example from earlier with the white box located at the top left corner of the blue parent element. By changing the value of the position property and specifying the coordinates of the new position, we can move the white box.

  • HTML
  • CSS (SCSS)
html
css

External relative positioning#

What if we want to position a child element outside of a parent element? We can position boxes tangent to the parent element by using the same initial method described above, relative and absolute values. Getting the child element outside of the parent may seem tricky at first, but just requires a bit of thinking outside the box. If we use percentages instead of specifying specific values.

As a general rule, it is better to avoid specific values as they can make your web applications less flexible and more prone to bugs.

Using the previous example, let’s say we want the child box to be positioned on the right edge of the blue box just at the upper right corner.

Try changing the left property to 100% and see where the white div goes.

It may not be readily apparent, but the white div is off the right side of the window. Since the value is set to 100%, we need to assign it to the property opposite the edge to which we want the element to be repositioned.

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.

It is recommended when building large stylesheets with extensive variables that we code in SCSS or SASS instead of pure CSS.

CSS variables or cascading variables, also called custom properties, are the key to establishing a theme. More specifically, the fact that CSS variables are inherited is the key. Inheritance means that we can attribute some variables to certain sections of our app and even override them in child components if necessary.

We can easily create, customize, and implement consistent themes throughout your web projects with the css-theming package. CSS-Theming is an npm package that will need to be installed and then imported using the JavaScript modules and SCSS src files.

Once css-theming is installed and set up, we can begin to customize it. The default settings for the package enable light and dark mode options, but there are plenty more CSS properties that can be changed.

The default theme inside the package looks like this:

$ct-themes: (
'default': (
'brightness': 'light',
// 'colors': overrides $colors-[light|dark]
// 'use-colors': if given, specifies which colors from the default palette to include
// 'colors-text-scale': overrides $colors-text-scale-[light|dark]
// 'semantic-colors': overrides $semantic-colors
// 'font': overrides $font
// 'text-color': overrides $text-color-[light|dark]
// 'bg-main': overrides $bg-main-[light|dark]
// 'bg-input': overrides $bg-input-[light|dark]
// 'swatches': overrides $swatches
// 'fg-target': overrides auto computed fg targets
// 'fg-swatches': overrides $fg-swatches-[light|dark]
// 'bg': overrides $bg-[light|dark]
// 'bg-focus': overrides $bg-focus-[light|dark]
// 'bd': overrides $bd-[light|dark]
// 'bd-focus': overrides $bd-focus-[light|dark]
),
'default-dark': (
'brightness': 'dark',
),
) !default;

Adding properties to the theme is simple.

$ct-themes: {
'default': {
'brightness': 'light',
'border-radius': .3em;
},
'default-dark': {
'brightness': 'dark',
'border-radius': .25em
}
}

After adding the border-radius property, it must be linked to a CSS variable so that it can be inserted in multiple places. There is even an SCSS mixin baked into the css-theming package. This mixin facilitates the variable linking process. Once the content is defined/linked it can be referenced throughout the stylesheet.

Responsive web design (RWD) is essential to modern web design. The practice of RWD instructs pages to intelligently scale their layouts based on the size of the screen it is being displayed on. By structuring media queries around breakpoints in the viewport sizing, we can create web pages that scale responsively.

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. They are a core pillar of responsive web design, and are a feature bespoke to CSS3. Assets are loaded with the @media at-rule if certain conditions are met. Commonly, media queries enable responsive design through breakpoints that are dependent on viewport dimensions.

Breakpoints are markers that tell the webpage to change its layout or load a different stylesheet at a specific width (usually in pixels).

Media queries are simple test expressions that are combined with logical and, or operators. They can be added to the @media and @import at-rules and can be used in the media attribute of <link> tags.

  • HTML
  • CSS (SCSS)
  • JavaScript
html
css
Resize the window you're reading this on to see the media query in action.

Below is a table of media query features. Most can be implemented with min- and max- prefixes to set ranges that test for requirements.

Feature

Description

color

Represents the number of bits per color with an integer

color-index

Represents the number of entries in the color lookup table with an integer

device-aspect-ratio

Describes the aspect ratio of a device with a w/h value, where w and h are integers

device-height

Represents the height of the output device with a length value (absolute or relative unit)

device-width

Represents the width of the output device with a length value

grid

Retrieves true for a grid-based device (does not support min- or max- prefixes)

height

Represents the height of the rendering surface with a length value

monochrome

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

resolution

Represents the resolution of the output device specified in dpi or dpcm

scan

Describes the scanning process of a tv media type. Values can be progressive or interlaced (does not support min- or max- prefixes)

width

Represents the width of the rendering surface with a length value


Animations are some of the most eye-catching aspects of CSS. You may think of these as pop-ups or notifications that bounce to attract attention, but clever animations can be used to aid the user experience and even the functionality of a website.

The basics of animation in CSS starts with the @keyframes at-rule.

Some of the main CSS properties for animations are as follows.

  • animation-name: determines the name of animation
  • animation-delay: creates a delay for the beginning of the animation
  • animation-iteration-count: defines the number of times the animation will run
  • animation-timing-function: defines the speed curve of the animation
    • linear: same speed from start to finish
    • ease: slow beginning and end
    • ease-in: slow beginning
    • ease-out: slow end
  • animation-duration: defines how long the animation will take to complete. The default for this value is 0, so if it is left unchanged then the animation will not occur.
  • animation direction: determines if the animation will play forwards or backwards
  • animation-fill-mode: determines 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.
    • 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 rules for both forward and backward

Below is a playground for you to sample some of these animation properties as executables.

  • HTML
  • CSS (SCSS)
  • JavaScript
html
css

The concept of animations in CSS is a long-winded topic and requires much more in depth attention than this brief section. If you wish to continue reading more about building your own animations in CSS, this blog: Animate CSS code: create a panda animation with HTML & CSS is a great place to start.

Thankfully, we don’t have to build every animation we want to implement in our web applications from scratch. There are open-source resources for you to download and incorporate into your own web sites. Thanks to a few benevolent and talented developers sharing their creations, anyone can create websites that are full of life. Two online databases that we encourage you to check out are:

Get hands on with CSS today.#

Try one of our 300+ courses and learning paths: The Complete Advanced Guide to CSS.

Wrap up and next steps#

Mastering CSS takes a long and concerted effort, and there is plenty more to learn than just the few scattered topics in this article. Hopefully you found at least some of these CSS tips useful, and have a solid idea of what to learn next. Prolific technical author and popular Educative course author, Ohans Emmanuel, put in a heroic effort to consolidate as much CSS knowledge as possible into one course. His course, The Complete Advanced Guide to CSS was recently updated to include fresh topics and new resources. Emmanuel writes clearly about common points of confusion such as pseudo-elements and pseudo-class selectors. The course requires no prior knowledge of CSS. It covers the basics first, and then dives into deeper, more advanced topics. Anyone is encouraged to start this course, from backend developers looking to expand their frontend knowledge to brand new developers that want to learn how to create gorgeous and expansive web applications.

If you’re just looking for a couple CSS magic tricks to learn, make sure you know how to:

  • add an ellipsis to responsive text
  • use the text-align property to center text
  • add a hover effect to interactable elements.

Happy learning!


Written By:
Tate Dorman
 
Join 2.5 million developers at
Explore the catalog

Free Resources