Payment of ₹ requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment Payment of ₹ requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment ⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig
Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label Techniques. Show all posts
Showing posts with label Techniques. Show all posts

Wednesday, October 14, 2026

Powerful CSS-Techniques For Effective Coding

 

Sometimes being a web-developer is just damn hard. Particularly coding is often responsible for slowing down our workflow, reducing the quality of our work and sleepless nights with pizza and coffee laying around the laptop. Reason: with a number of incompatibility issues and quite creative rendering engines it sometimes takes too much time to find a workaround for some problem without addressing browsers with quirky hacks. And that’s where ready-to-use solutions developed by other designers come in handy.

Sometimes being a web-developer is just damn hard. Particularly coding is often responsible for slowing down our workflow, reducing the quality of our work and sleepless nights with pizza and coffee laying around the laptop. Reason: with a number of incompatibility issues and quite creative rendering engines it sometimes takes too much time to find a workaround for some problem without addressing browsers with quirky hacks. And that’s where ready-to-use solutions developed by other designers come in handy.

One year ago we’ve published the post with 53 CSS-Techniques You Couldn’t Live Without where we provided references to the most useful CSS-techniques which are often used in almost every project. Over the last year we’ve been observing what’s happening with the CSS-based web-development, and we collected most useful CSS-techniques we’ve stumbled upon — for us and for our readers.

In this post we present 50 new CSS-techniques, ideas and ready-to-use solutions for effective coding. You definitely know some of them, but definitely not all of them. Some technique is missing? Let us know in the comments to this post.

Thanks to all developers who contributed to the CSS-based design over the last year. The community appreciates it.

CSS-Techniques

  1. CSS Server-Side Pre-Processor
CSS-Technique
  1. Advanced CSS Menu
CSS-techniques - Advanced CSS Menu
  1. Styling File Inputs with CSS and the DOM

File inputs (<input type=“file” />) are the bane of beautiful form design. No rendering engine provides the granular control over their presentation designers desire. This simple, three-part progressive enhancement provides the markup, CSS, and JavaScript to address the long-standing irritation.

CSS-Technique
  1. A Savvy Approach to Copyright Messaging

Derek Powazek suggests adding a copyright message to a photo and use CSS to crop its view. This is supposed to accomplish the goal of adding robust copyright information without defacing your own work.

Screenshot
  1. Advanced CSS Menu Trick

What we want to do here, is instead of simply altering the state of the navigation item the user is currently rolling over, we want to alter the non navigation items as well.

Screenshot
  1. CSS hover effect
CSS-techniques - CSS hover effect | Veerle's blog
  1. Creating a table with dynamically highlighted columns like Crazy Egg’s pricing table
CSS-techniques - Creating a table with dynamically highlighted columns like Crazy Egg's pricing table
  1. Rediscovering the Button Element
CSS-techniques - Particletree » Rediscovering the Button Element
  1. A CSS styled table version 2
CSS-techniques - A CSS styled table version 2 | Veerle's blog
  1. CSS Step Menu

A method of designing the so-called step-menus, which have some steps users have to go through in order to achieve some aim. This menu offers a varying amount of steps, dependent upon the type of user accessing the application.

Stepmenu

  1. Creating bulletproof graphic link buttons with CSS | 456 Berea Street
CSS-techniques - Creating bulletproof graphic link buttons with CSS | 456 Berea Street
  1. Better Ordered Lists (Using Simple PHP and CSS)

Ordered lists are boring! Sure you can apply background images and do quite a bit of sprucing up to a regular ordered list, but you just don’t get enough control over the number itself.

Screenshot
  1. CSS Dock Menu
CSS-techniques - CSS Dock Menu
  1. Fade Out Bottom

This is a demonstration of the effect where the bottom of the page seems to fade out. The technique makes use of an fixed position div (bottom: 0%) with a transparent PNG image and a high z-index value.

CSS-techniques - Fade Out Bottom
  1. How to Style an A to Z Index with CSS
CSS-techniques - How to Style an A to Z Index with CSS | Smiley Cat Web Design
  1. CSS List Boxes

Using a simple unordered list this experiment aligns the boxes across the page with the end result being to showcase items like services, products, or specials. One of cool thing about this — if you turn off styles — is the extractable semantics with the headings and paragraphs used.

List Boxes

  1. How-to create a “Table of Contents” Navigation

In as little as 8 lines of HTML, and 5 lines of CSS, the Table Of Contents Navigation block can be integrated in your site ready for even more styling.

Table of Contents

  1. CSS Recipe for Success
CSS-techniques - CSS - A Recipe for Success
  1. Partial Opacity
CSS-techniques - Stu Nicholls | CSSplay | Partial Opacity
  1. CSS Double Lists
CSS-techniques - CSS: Double Lists | Mike’s Experiments | MikeCherim.com
  1. Perspective Text with CSS
CSS-techniques - Mike’s Experiments: Archives Page | A Record of My Madness | Powered by the GreenBeast CMS RSS Newsmaker - -
  1. Better Email Links: Featuring CSS Attribute Selectors

Learn how to generate code for displaying the e-mail automatically once mailto is used. CSS Attribute Selectors in action which is not supported by Internet Explorer 6 and 7.

Screenshot
  1. CSS: Menu Descriptions

This is a CSS technique that could be useful if you want to give users accessible added content such as tool-tips, notifications, or alerts, without adding unnecessary clutter to your page. And since it doesn’t rely of JavaScript, it should be useful to everyone, even disabled users.

Screenshot

Further Techniques #

  1. CSS Transparency Settings for All Browsers
CSS-techniques - CSS Transparency Settings for All Browsers
  1. Custom Reading Containers

This amazing little script allows the user to resize any container.

  1. Eric Meyer’s CSS Reset
CSS-techniques - CSS Tools: Reset CSS
  1. PNG Overlay

Create a transparent PNG overlay which can be used as a mask / frame around regular JPEG or GIF so users can upload photos without having to worry about using any graphics program to apply filters, plus it saves time.

  1. Turning Lists into Trees
CSS-techniques - odyniec.net
  1. Create Resizable Images With CSS
CSS-techniques - Create Resizable Images With CSS | Smiley Cat Web Design

70 Expert Ideas For Better CSS Coding

 

CSS isn’t always easy to deal with. Depending on your skills and your experience, CSS coding can sometimes become a nightmare, particularly if you aren’t sure which selectors are actually being applied to document elements. An easy way to minimize the complexity of the code is as useful as not-so-well-known CSS attributes and properties you can use to create a semantically correct markup. We’ve taken a close look at some of the most interesting and useful CSS tricks, tips, ideas, methods, techniques and coding solutions and listed them below.

CSS isn’t always easy to deal with. Depending on your skills and your experience, CSS coding can sometimes become a nightmare, particularly if you aren’t sure which selectors are actually being applied to document elements. An easy way to minimize the complexity of the code is as useful as not-so-well-known CSS attributes and properties you can use to create a semantically correct markup.

We’ve taken a close look at some of the most useful CSS tricks, tips, ideas, methods, techniques and coding solutions and listed them below. We also included some basic techniques you can probably use in every project you are developing, but which are hard to find once you need them.

And what has come out of it is an overview of over 70 expert CSS ideas which can improve your efficiency of CSS coding. You might be willing to check out the list of references and related articles in the end of this post.

We’d like to express sincere gratitude to all designers who shared their ideas, techniques, methods, knowledge and experience with their readers. Thank you, we, coders, designers, developers, information architects - you name it - really appreciate it.

You might be interested in reading our article 53 CSS-Techniques You Couldn’t Live Without, which should provide you with a basic toolbox for CSS-based techniques you might use in your next projects.

1.1. Workflow: Getting Started

  • After you have a design, start with a blank page of content. “Include your headers, your navigation, a sample of the content, and your footer. Then start adding your html markup. Then start adding your CSS. It works out much better.” [CSSing]
  • Use a master stylesheet. “One of the most common mistakes I see beginners and intermediates fall victim to when it comes to CSS is not removing the default browser styling. This leads to inconsistencies in the appearance of your design across browsers, and ultimately leaves a lot of designers blaming the browser. It is a misplaced blame, of course. Before you do anything else when coding a website, you should reset the styling.” Master Stylesheet: The Most Useful CSS Technique, Ryan Parr

    master.css
    @import url("reset.css");
    @import url("global.css");
    
    @import url("flash.css");
    @import url("structure.css");
    
  • Reset your CSS-styles first. “You can often eliminate the need to specify a value for a property by taking advantage of that property’s default value. Some people like doing a Global white space reset by zeroing both margin and padding for all elements at the top of their stylesheets. [Roger Johansson]

  • Keep a library of helpful CSS classes. Useful for debugging, but should be avoided in the release version (separate markup and presentation). Since you can use multiple class names (i.e. <p class="floatLeft alignLeft width75">...</p>), make use of them debugging your markup. (updated) [Richard K. Miller]

    CSS:
    .width100 { width: 100%; }
    .width75 { width: 75%; }
    .width50 { width: 50%; }
    .floatLeft { float: left; }
    .floatRight { float: right; }
    .alignLeft { text-align: left; }
    .alignRight { text-align: right; }
    
  • Eric Meyer’s Global Reset, Christian Montoya’s initial CSS file, Mike Rundle’s initial CSS file.

1.2. Organize your CSS-code

  • Organize your CSS-styles, using master style sheets. “Organizing your CSS helps with future maintainability of the site. Start with a master style sheet. Within this style sheet import your reset.css, global.css, flash.css (if needed) and structure.css and on occasion a typography style sheet. Here is an example of a “master” style sheet and how it is embedded in the document:”

    h2 { }
    #snapshot_box h2 {
        padding: 0 0 6px 0;
        font: bold 14px/14px "Verdana", sans-serif; }
    #main_side h2 {
        color: #444;
        font: bold 14px/14px "Verdana", sans-serif; }
    .sidetagselection h2 {
        color: #fff;
        font: bold 14px/14px "Verdana", sans-serif; }
    
  • Organize your CSS-styles, using flags. “Divide your stylesheet into specific sections: i.e. Global Styles – (body, paragraphs, lists, etc), Header, Page Structure, Headings, Text Styles, Navigation, Forms, Comments, Extras. [5 Tips for Organizing Your CSS]

    /* -----------------------------------*/
    /* ---------->>> GLOBAL <<<-----------*/
    /* -----------------------------------*/
    
  • Organize your CSS-styles, making a table of contents. At the top of your CSS document, write out a table of contents. For example, you could outline the different areas that your CSS document is styling (header, main, footer etc). Then, use a large, obvious section break to separate the areas.

  • Organize your CSS-styles, ordering properties alphabetically. “I don’t know where I got the idea, but I have been alphabetizing my CSS properties for months now, and believe it or not, it makes specific properties much easier to find.” [Christian Montoya]

    body {
        background: #fdfdfd;
        color: #333;
        font-size: 1em;
        line-height: 1.4;
        margin: 0;
        padding: 0;
    }
    
  • Separate code into blocks. “This might be common sense to some of you but sometimes I look at CSS and it’s not broken down into “sections.” It’s easy to do an it makes working with code weeks, months, or years later much easier. You’ll have an easier time finding classes and elements that you need to change. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks]

  • Hook, line, and sinker. Once you have your CSS and sections in place start considering where your selector “hooks” will live by using structural hooks in your mark up. This is your saving grace for future editing and maintenance of the site. This will also give you strength in your document.” [Ryan Parr]

  • Break your style sheet in separate blocks. “I break down my style sheet into three separate blocks. The first is straight element declarations. Change the body, some links styles, some header styles, reset margins and padding on forms, and so on. […] After element declarations, I have my class declarations; things like classes for an error message or a callout would go here. [..] I start by declaring my main containers and then any styles for elements within those containers are indented. At a quick glance, I can see how my page is broken down and makes it easier to know where to look for things. I’ll also declare containers even if they don’t have any rules.” [Jonathan Snook]

1.3. Workflow: Handling IDs, Classes, Selectors, Properties

  • Keep containers to a minimum. “Save your document from structural bloat. New developers will use many div’s similar to table cells to achieve layout. Take advantage of the many structural elements to achieve layout. Do not add more div’s. Consider all options before adding additional wrappers (div’s) to achieve an effect when using a little nifty CSS can get you that same desired effect.” [Ryan Parr]
  • Keep properties to a minimum. “Work smarter, not harder with CSS. Under this rule, there are a number of subrules: if there isn’t a point to adding a CSS property, don’t add it; if you’re not sure why you’re adding a CSS property, don’t add; and if you feel like you’ve added the same property in lots of places, figure out how to add it in only one place.” [CSSing]
  • Keep selectors to a minimum. “Avoid unnecessary selectors. Using less selectors will mean less selectors will be needed to override any particular style — that means it’s easier to troubleshoot.” [Jonathan Snook]
  • Keep CSS hacks to a minimum. “Don’t use hacks unless its a known and documented bug. This is an important point as I too often see hacks employed to fix things that aren’t really broken in the first place. If you find that you are looking for a hack to fix a certain issue in your design then first do some research (Google is your friend here) and try to identify the issue you are having problems with. [10 Quick Tips for an easier CSS life]
  • Use CSS Constants for faster development. “The concept of constants – fixed values that can be used through your code [is useful]. [..] One way to get round the lack of constants in CSS is to create some definitions at the top of your CSS file in comments, to define ‘constants’. A common use for this is to create a ‘color glossary’. This means that you have a quick reference to the colors used in the site to avoid using alternates by mistake and, if you need to change the colors, you have a quick list to go down and do a search and replace.” [Rachel Andrew]

    # /*
    # Dark grey (text): #333333
    # Dark Blue (headings, links) #000066
    # Mid Blue (header) #333399
    # Light blue (top navigation) #CCCCFF
    # Mid grey: #666666
    # */
    
  • Use a common naming system. Having a naming system for id’s and classes saves you a lot of time when looking for bugs, or updating your document. Especially in large CSS documents, things can get a big confusing quickly if your names are all different. I recommend using a parent_child pattern. [10 CSS Tips]

  • Name your classes and IDs properly, according to their semantics. “We want to avoid names that imply presentational aspects. Otherwise, if we name something right-col, it’s entirely possible that the CSS would change and our “right-col” would end up actually being displayed on the left side of our page. That could lead to some confusion in the future, so it’s best that we avoid these types of presentational naming schemes. [Garrett Dimon]

  • Group selectors with common CSS declarations. “Group selectors. When several element types, classes, or id:s share some properties, you can group the selectors to avoid specifying the same properties several times. This will save space – potentially lots of it.” [Roger Johansson]

  • Isolate single properties that you are likely to reuse a lot. “If you find yourself using a single property a lot, isolate it to save yourself repeating it over and over again and also enabling you to change the display of all parts of the site that use it.”

  • Move ids and class naming as far up the document tree as you can. Leverage contextual selectors as much as possible. Don’t be afraid to be verbose in your selectors. Longer selectors can make css documents easier to read while also cutting down the chances of developing class- or divitis. [Chric Casciano]

  • Learn to exploit the cascading nature of CSS. “Say you have two similar boxes on your website with only minor differences - you could write out CSS to style each box, or you could write CSS to style both at the same time, then add extra properties below to make one look different.”

  • Use Your Utility Tags: <small>, <em> and <strong>. “Many times you’ll have a section in your design that calls for various typographical weights/looks all on the same line, or very close to each other. drop in random divs and classes because I feel they’re not semantic and defeat the purpose of your nice XHTML everywhere else.” Instead, use semantic tags. [Mike Rundle’s 5 CSS Tips]

1.4. Workflow: Use shorthand notation

  • Shorten hexadecimal colour notation. “In CSS, when you use hexadecimal colour notation and a colour is made up of three pairs of hexadecimal digits, you can write it in a more efficient way by omitting every second digit: #000 is the same as #000000, #369 is the same as #336699 [Roger Johansson]
  • Define pseudo classes for links in the LoVe/HAte-order: Link, Visited, Hover, Active. “To ensure that you see your various link styles, you’re best off putting your styles in the order “link-visited-hover-active”, or “LVHA” for short. If you’re concerned about focus styles, they may go at the end– but wait until you’ve read this explanation before you decide.” [Eric Meyer]

    a:link { color: blue; }
    a:visited { color: purple; }
    a:hover { color: purple; }
    a:active { color: red; }
    
  • Define element’s margin, padding or border in TRouBLed-order: Top, Right, Bottom, Left. “When using shorthand to specify an element’s margin, padding or border, do it clockwise from the top: Top, Right, Bottom, Left.” [Roger Johansson]

  • You can use shorthand properties. “Using shorthand for margin, padding and border properties can save a lot of space.

    CSS:
    margin: top right bottom left;
    margin: 1em 0 2em 0.5em;
    (margin-top: 1em; margin-right: 0; margin-bottom: 2em; margin-left: 0.5em;)
    
    CSS:
    border: width style color;
    border: 1px solid #000;
    
    CSS:
    background: color image repeat attachment position;
    background: #f00 url(background.gif) no-repeat fixed 0 0;
    
    CSS:
    font: font-style (italic/normal) font-variant (small-caps) font-weight font-size/line-height font-family;
    font: italic small-caps bold 1em/140% "Lucida Grande",sans-serif;
    

1.5. Workflow: Setting Up Typography

  • **To work with EMs like with pxs, set font-size on the body-tag with 62.5%**. Default-value of the font-size is 16px; applying the rule, you’ll get one Em standing for roughly ten pixels (16 x 62.5% = 10). “I tend to put a font-size on the body tag with value: 62.5%. This allows you to use EMs to specify sizes while thinking in PX terms, e.g. 1.3em is approximately 1.3px. ” [Jonathan Snook]
  • Use universal character set for encoding. “[..] The answer is to use a single universal character set that’s able to cover most eventualities. Luckily one exists: UTF-8, which is based on Unicode. Unicode is an industry standard that’s designed to enable text and symbols from all languages to be consistently represented and manipulated by computers. UTF- 8 should be included in your web page’s head like this. [.Net Magazine 20 pro tips]

  • You can change capitalisation using CSS. If you need something written in capitals, such as a headline, rather than rewriting the copy, let CSS do the donkey work. The following code will transform all text with an h1 attribute into all capitals, regardless of format”. [.Net Magazine 20 pro tips]

    h1 {
        text-transform: uppercase;
    }
    
  • You can display text in small-caps automatically. The font-variant property is used to display text in a small-caps font, which means that all the lower case letters are converted to uppercase letters, but all the letters in the small-caps font have a smaller font-size compared to the rest of the text.

    h1 {
        font-variant: small-caps;
    }
    
  • Cover all the bases - define generic font-families. “When we declare a specific font to be used within our design, we are doing so in the hope that the user will have that font installed on their system. If they don’t have the font on their system, then they won’t see it, simple as that. What we need to do is reference fonts that the user will likely have on their machine, such as the ones in the font-family property below. It is important that we finish the list with a generic font type. [Getting into good coding habits]

    p {
        font-family: Arial, Verdana, Helvetica, sans-serif;
    }
    
  • Use 1.4em - 1.6em for line-height. “line-height:1.4” for readable lines, reasonable line-lengths that avoid lines much longer than 10 words, and colors that provide contrast without being too far apart. For example, pure black on pure white is often too strong for bright CRT displays, so I try to go with an off-white (#fafafa is a good one) and a dark gray (#333333, another good one).” [Christian Montoya]

  • Set 100.01% for the html-element. This odd 100.01% value for the font size compensates for several browser bugs. First, setting a default body font size in percent (instead of em) eliminates an IE/Win problem with growing or shrinking fonts out of proportion if they are later set in ems in other elements. Additionally, some versions of Opera will draw a default font-size of 100% too small compared to other browsers. Safari, on the other hand, has a problem with a font-size of 101%. The current “best” suggestion is to use the 100.01% value for this property.” [CSS: Getting into good habits]

1.6. Workflow: Debugging

  • Add borders to identify containers. “Use plenty of test styles like extra borders or background colors when building your documents or debugging layout issues. div { border:1px red dashed; } works like a charm. There are also bookmarklets that apply borders and do other things for you.” You can also use * { border: 1px solid #ff0000; }. [Chric Casciano]. Adding a border to specific elements can help identify overlap and extra white space that might not otherwise be obvious. [CSS Crib Sheet]

    * { border: 1px solid #f00; }
    
  • Check for closed elements first when debugging. “If you ever get frustrated because it seemed like you changed one minor thing, only to have your beautiful holy-grail layout break, it might be because of an unclosed element. [10 CSS Tips]

2.1. Technical Tips: IDs, Classes

  • 1 ID per page, many classes per page. “Check your IDs: Only one element in a document can have a certain value for the id attribute, while any number of elements can share the same class name. [..] Class and id names can only consist of the characters [A-Za-z0-9] and hyphen (-), and they cannot start with a hyphen or a digit (see CSS2 syntax and basic data types).” [Roger Johansson]
  • Element names in selectors are case sensitive. “Remember case sensitivity. When CSS is used with XHTML, element names in selectors are case sensitive. To avoid getting caught by this I recommend always using lowercase for element names in CSS selectors. Values of the class and id attributes are case sensitive in both HTML and XHTML, so avoid mixed case for class and id names.” [Roger Johansson]
  • CSS classes and IDs must be valid. “I.e. beginning with a letter, not a number or an underscore. IDs must be unique. Their names should be generic, describe functionality rather than appearance.” [CSS Best Practices]
  • You can assign multiple class names to a given element. “You can assign multiple class names to an element. This allows you to write several rules that define different properties, and only apply them as needed.” [Roger Johansson]

2.2. Technical Tips: Use the power of selectors

Roger Johansson has written an extremely useful series of articles about CSS 2.1 Selectors. These articles are highly recommended to read - some useful aspects can be found in the list below. Note that selectors ‘>’ and ‘+’ aren’t supported in IE6 and earlier versions of Internet Explorer (updated).

  • You can use child selectors. “A child selector targets an immediate child of a certain element. A child selector consists of two or more selectors separated by a greater than sign, “>”. The parent goes to the left of the “>”, and whitespace is allowed around the combinator. This rule will affect all strong elements that are children of a div element. [Roger Johansson]

    div > strong { color:#f00; }
    
  • You can use adjacent sibling selectors. An adjacent sibling selector is made up of two simple selectors separated by a plus sign, “+”. Whitespace is allowed around the adjacent sibling combinator. The selector matches an element which is the next sibling to the first element. The elements must have the same parent and the first element must immediately precede the second element. [Roger Johansson]

    p + p { color:#f00; }
    
  • You can use attribute selectors. Attribute selectors match elements based on the presence or value of attributes. There are four ways for an attribute selector to match:

    [att]
    Matches elements that have an att attribute, regardless of its value.
    [att=val]
    Matches elements that have an att attribute with a value of exactly “val”.
    [att~=val]
    Matches elements whose att attribute value is a space-separated list that contains “val”. In this case “val” cannot contain spaces.
    [att|=val]
    Matches elements whose att attribute value is a hyphen-separated list that begins with “val”. The main use for this is to match language subcodes specified by the lang attribute (xml:lang in XHTML), e.g. “en”, “en-us”, “en-gb”, etc.
    
  • The selector in the following rule matches all p elements that have a title attribute, regardless of which value it has:

    p[title] { color:#f00; }
    
  • The selector matches all div elements that have a class attribute with the value error:

    div[class=error] { color:#f00; }
    
  • Multiple attribute selectors can be used in the same selector. This makes it possible to match against several different attributes for the same element. The following rule would apply to all blockquote elements that have a class attribute whose value is exactly “quote”, and a cite attribute (regardless of its value):

    blockquote[class=quote][cite] { color:#f00; }
    
  • You should use descendant selectors. “Descendant selectors can help you eliminate many class attributes from your markup and make your CSS selectors much more efficient. ” [Roger Johansson]

  • Be careful when styling links if you’re using anchors. “If you use a classic anchor in your code (<a name="anchor">) you’ll notice it picks up :hover and :active pseudo-classes. To avoid this, you’ll need to either use id for anchors instead, or style with a slightly more arcane syntax: :link:hover, :link:active” [Dave Shea]
  • Define relationships for links. “The rel attribute is supposed to indicate a semantic link relationship from one resource to another.

    a[rel~="nofollow"]::after {
        content: "2620";
        color: #933;
        font-size: x-small;
    }
    a[rel~="tag"]::after {
        content: url(https://www.technorati.com/favicon.ico);
    }
    
  • “These make use of the attribute selector for space separated lists of values. Any a element with a relationship containing those values will be matched. Links with the nofollow relationship will be followed by a dark red skull and crossbones (?) and those with the tag relationship will be followed by the Technocrati icon.” [Handy CSS]

  • You can mark external links automatically. Many people make use of the non-standard rel="external" relationship to indicate a link to an external site. However, adding that to each and every link is time consuming and and unnecessary. This style rule will place an north east arrow after any link on your site to an external site. [Handy CSS]

    a[href^="https://"]:not([href*="smashingmagazine.com"])::after {
        content: "2197";
    }
    
  • You can remove dotted links with outline: none;. To remove dotted links use outline: none;:

    a:focus {
        outline: none;
    }
    

2.4. Technical Tips: CSS-Techniques

  • You can specify body tag ID. “In most cases placing an ID in the body tag will allow you manipulate CSS presentational items and markup elements by page by page basis. Not only will you be able to organize your sections you will be able to create multiple CSS presentations without changing your markup from template to template or page to page.” [Ryan Parr, Invasion of Body Switchers]
  • You can create columns with equal heights with CSS. Equal Height Technique: a method to make all columns appear to be the same height. But without the need for faux column style background images. Faux Columns: with background images.
  • You can align vertically with CSS. “Say you have a navigation menu item whose height is assigned 2em. Solution: specify the line height to be the same as the height of the box itself in the CSS. In this instance, the box is 2em high, so we would insert line-height: 2em into the CSS rule and the text now floats in the middle of the box!”
  • You can use pseudo-elements and classes to generate content dynamically. Pseudo-classes and pseudo-elements. Pseudo-classes and pseudo-elements can be used to format elements based on information that is not available in the document tree. For example, there is no element that refers to the first line of a paragraph or the first letter of an element’s text content. You can use :first-child, :hover, :active, :focus, :first-line, :first-letter, :before, :after and more.
  • You can set <hr> to separate posts beautifully. “Restyling the horizontal rule (
    ) with an image can be a beautiful addition to a web page. [CSS: Best Practices]
  • You can use the same navigation (X)HTML-code on every page. “Most websites highlight the navigation item of the user’s location in the website. But it can be a pain as you’ll need to tweak the HTML code behind the navigation for each and every page. So can we have the best of both worlds?” [Ten More CSS Tricks you may not know]

    _XHTML:_
    
  • Insert an id into the <body> tag. The id should be representative of where users are in the site and should change when users move to a different site section.

    CSS:
    #home .home, #about .about, #contact .contact
    {
        commands for highlighted navigation go here
    }
    
  • You can use margin: 0 auto; to horizontally centre the layout. “To horizontally centre an element with CSS, you need to specify the element’s width and horizontal margins.” [Roger Johansson]

    _XHTML:_
    
    CSS:
    #wrap {
    width:760px; /* Change this to the width of your layout */
    
    margin:0 auto;
    }
    
  • You can add CSS-styling to RSS-feeds. “You can do a lot more with an XSL stylesheet (turn links into clickable links, etc), but CSS can make your feed look much less scary for the non-technical crowd. [Pete Freitag]

    <?xml version="1.0" ?>
    <?xml-stylesheet type="text/css" href="https://you.com/rss.css" ?>
    
    ...
    
  • You can hide CSS from older browsers. “A common way of hiding CSS files from old browsers is to use the @import trick. [Roger Johansson]

    @import "main.css";
    
  • Always declare margin and padding in block-level elements. [10 CSS Tips]

  • Set a width OR margin and padding. “My rule of thumb is, if I set a width, I don’t set margin or padding. Likewise, if I’m setting a margin or padding, I don’t set a width. Dealing with the box model can be such a pain, especially if you’re dealing with percentages. Therefore, I set the width on the containers and then set margin and padding on the elements within them. Everything usually turns out swimmingly.” [Jonathan Snook]

  • Avoid applying padding/borders and a fixed width to an element. “IE5 gets the box model wrong, which really makes a mess of things. There are ways around this, but it’s best to side-step the issue by applying the padding to the parent element instead of the child that gets a fixed-width. [CSS Crib Sheet]

  • Provide print styles. “You can add a print stylesheet in exactly the same way that you would add a regular stylesheet to your page:

    _or_
    
  • This ensures that the CSS will only apply to printed output and not affect how the page looks on screen. With your new printed stylesheet you can ensure you have solid black text on a white background and remove extraneous features to maximise readability. More about CSS-based print-Layouts.

2.5. Technical Tips: IE Tweaks

  • You can force IE to apply transparence to PNGs. “In theory, PNG files do support varied levels of transparency; however, an Internet Explorer 6 bug prevents this from working cross-browser.” [CSS Tips, Outer-Court.com]

    #regular_logo
    {
        background: url('test.png'); width:150px; height:55px;
    }
    /*  */
    * html #regular_logo
    {
        background:none;
        float:left;
        width:150px;
        filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='test.png', sizingMethod='scale');
    }
    /* */
    
  • You can define min-width and max-width in IE. You can use Microsoft’s dynamic expressions to do that. [Ten More CSS Trick you may not know]

    #container
    {
        min-width: 600px;
        max-width: 1200px;
        width:expression(document.body.clientWidth < 600? "600px" : document.body.clientWidth > 1200? "1200px" : "auto");
    }
    
  • You can use Conditional Comments for IE. “The safest way of taking care of IE/Win is to use conditional comments. It feels more future-proof than CSS hacks – is to use Microsoft’s proprietary conditional comments. You can use this to give IE/Win a separate stylesheet that contains all the rules that are needed to make it behave properly. ” [Roger Johansson]

Workflow: Get Inspired

  • Play, experiment with CSS. “Play. Play with background images. Play with floats.” [Play with positive and negative margins. Play with inheritance and cascading rules. Play. [Chric Casciano]
  • Learn from others. Learn from great sites built by others. Any site’s HTML is easily accessible by viewing a page’s source code. See how others have done things and apply their methods to your own work. [.Net Magazine 20 pro tips]

 

Sunday, October 11, 2026

Designing With Grid-Based Approach

 

The main idea behind grid-based designs is a solid visual and structural balance of web-sites you can create with them. Sophisticated layout structures offer more flexibility and enhance the visual experience of visitors. In fact, users can easier follow the consistency of the page, while developers can update the layout in a well thought-out, consistent way. However, it’s quite hard to find your way through all the theory behind grid systems: it isn’t easy at all. Some important notions and related key-facts can help to learn basics and keep essential techniques in mind.

The main idea behind grid-based designs is a solid visual and structural balance of web-sites you can create with them. Sophisticated layout structures offer more flexibility and enhance the visual experience of visitors. In fact, users can easier follow the consistency of the page while developers can update the layout in a well thought-out, consistent way. However, it’s quite hard to find your way through all the theory behind grid systems: it isn’t easy at all. Some important notions and related key facts can help to learn basics and keep essential techniques in mind.

And this is what this article is all about. Inspired by Khoi Vinn’s and Mark Boulton’s presentation Grids are Good, we’ve decided to take a deep look in the articles about grid-based designs. We’ve read through over 50 articles and selected some of the most important and interesting facts web-developers should know about the grid-based approach. Besides, we’ve listed the most useful references, tutorials and tools we found - with precise descriptions of what the articles are about.

Examples of Grid-based design in 2027

But first few examples of grid-based designs to make clear what the article is about.

Screenshot of the UX Mag homepage
Screenshot of the New York Times homepage
Screenshot of the Times Online homepage
Screenshot of Jeff Crofts homepage
Screenshot of an article at the Guardian Online
Screenshot of the Subtraction website

Things You Probably Don’t Know About Grid-based Design

  • “The grid is the most vivid manifestation of the will to order in graphic design. […] Units are the basic buildung block of a grid. They’re all uniform. Columns are the grouping of units that create the visual structure of the page. They are not necessary uniform.”
  • “A grid is a consistent system for placing objects. It works on two levels: At the unit level of cells (e.g. 20x20 pixels) and at the column level (e.g. 4 columns).” [ Grid-based Layout ].
  • “A balanced and consistently implemented design scheme will increase readers’ confidence in your site. […] Your first step is to establish a basic layout grid. With this graphic “backbone” you can determine how the major blocks of type and illustrations will regularly occur in your pages. [..] To start, gather representative examples of your text, along with some graphics, scans, or other illustrative material, and experiment with various arrangements of the elements on the page. […] Your goal is to establish a consistent, logical screen layout, one that allows you to “plug in” text and graphics without having to stop and rethink your basic design approach on each new page.”
  • “One of the larger problems in working with grids in web pages is that you often can’t do much about vertical proportions. Often your content is dynamic, so the best you can do is approximate. […] So the focus is usually on the horizontal layout, which usually means columns.” [ Dave Shea ]
  • “On the Web, vertical rhythm – the spacing and arrangement of text as the reader descends the page – is contributed to by three factors: font size, line height and margin or padding. [..] The basic unit of vertical space is line height.” [ Richard Rutter ]
  • “In order that typographic integrity is maintained when text is resized by the user we must use ems for all our vertical measurements, including line-height, padding and margins.” [ Richard Rutter ]
  • “Designing Grid Systems in Graphic Design, 1. figure out the page size, 2. divide it into a grid, 3. start designing”. [ Josef Muller-Brockmann’s “Grid Systems in Graphic Design” ]
  • “Use the canonical grid to adjust the sizes and positions of elements across rows. Short elements are extended to begin and end on grid boundaries, while long elements are allowed to span multiple grid units or are shortened to fit within the standard unit. In this way, the grid is merely being used to help establish consistent alignment relationships. […] For dynamic layouts, identifying the minimum size that can be accomodated by the layout is usually a better solution than trying to recompute the layout for arbitrarily small display sizes.” [ Module and Program ]
  • “One of the most effective principles in grid design is called the Rule of Thirds, also known as the golden grid rule. The Rule of Thirds is a technique which is applied by dividing a space into thirds, both vertically and horizontally, creating a grid of rectangles.” — Mark Boulton
  • “The Golden Section, Golden Ratio, and the grandiose Divine Proportion are all names for the same thing; a ratio of 1.618. Nodding off? Not yet? Good! Bear with me. Here?s the maths: the Golden Ratio is the ratio between two segments so that the ratio between point ac/bc is 1.618.” — Mark Boulton. You can also use Phiculator for your grids.
  • “The Golden Section is a ratio which is evident throughout the universe as the number Phi. You can use this ratio to good effect in design by making sure that elements of your grid conform to this ratio. Using the Golden Section can ensure a natural sense of correct composition, even though it is based in mathematics it will ‘feel’ right.” — Mark Boulton
  • “Grid Structures: Once you have answered most of the questions regarding the content, format and typography, you should begin sketching out grid structures based on the appropriate page sizes and formats. You should first begin by defining the Type Area. The Type Area is the area where your grid will be contained. It is surrounded on all sides by margins and in some cases running heads and page footers, numbers, marginalia, etc.” [ Typographic Grids ]
  • “The main principle of the baseline grid is that the bottom of every line of text (the baseline) falls on a vertical grid set in even increments all the way down the page.” [ Wilson Miner ]
  • “You can use relative sizes, but it quickly becomes a lot more difficult to maintain as the math becomes more complicated. It’s easy to get 12 out of 18 (just set the line-height to 1.5em), but when you want to adjust the text size but keep the same line-height, the fractions start to get messy”. [ Wilson Miner ]
  • “Table layouts are great for grid designs. The markup itself reproduces a specific grid, and the tendency is for us to just fill up the boxes with the images, type, and interface elements that make up our design.” [ Molly Holzschlag ]
  • “Ratios are at the core of any well designed grid system. [..] By using the size of the paper as a guide we can divide using that ratio to begin creating the grid. You can see this through diagrams 1 - 6 that we begin by simply layering division upon division to slowly build up the grid.” [ Mark Boulton ]
  • “Well designed grid systems can make your designs not only more beautiful and legible, but more usable.” [ Mark Boulton ]
  • “Gutters are the gaps in between columns. They are there so text, or image, from different columns don’t run into each other. In grid system design sometimes, depending on what theory you read, gutters are seperate to the columns.” [ Mark Boulton ]
  • “The thing about designing to grids is that in order for the grid to work you must consistently align items on the grid lines.” [ Mark Boulton ]
  • “One of the most useful ‘tools’ for creating pixel-perfect grid systems for the web is Khoi’s superb idea of using a grid as a background-image element on the body tag. To summarise: Using the grid I designed in photoshop, I save it out as a gif and then apply that to the background of the body tag. This provides me, throughout the build of the site, the grid so I can align all the content elements accordingly.” [ Mark Boulton ]
  • “In your page layout, you’ve probably set margins. These margins often show up as light solid or dashed lines on the screen. These top, bottom, left, and right margins create a box in the middle of your page. Stop there and you have a single unit grid. Further divide the page into uniform parts and you’ve created a multiple unit grid.” [ Jacci Howard Bear ]
  • “Grid units are the primary locations on your page where you will place text and images. They determine placement not necessarily size. That is, if you have a graphic image that is larger than your grid unit, it doesn’t mean you can’t use it. ” [ Jacci Howard Bear ]
  • “1, 2, and 3 column grids are common. Each can accommodate lots of text, especially long articles. [..] 4 or more columns offer greater flexibility for publications with text, photos, and other graphic elements and a mix of long and short articles. [..] Grids based on an even number of grid columns can suffer from too much symmetry if text and graphics are confined to individual or double grid columns throughout.” [ Grids - Flexible Options ]
  • “A grid is made up of vertical and horizontal lines and is the foundation of nearly every type of visual media. The structure is there to shape the content into proportions that are pleasing to the eye.” [ Anne Van Wagener ]
  • “To add flexibility you can break the grid down into 10 or 12 columns. Half-columns are a good place to anchor mug-shots, refers, and other info.” [ Anne Van Wagener ]
  • “You can have more than one grid. Your front page could be based on a five column grid while inside pages with ads on a six column. There is no one right way.” [ Anne Van Wagener ]
  • “The grid is the mannequin and the comp is the pattern. [..] Using the grid-based design comps provided me with units of measurement that I could easily turn into divs for the style sheet. I figure out the areas of content in the same way I would work with a wireframe to block out content and graphics. I come up with a naming scheme for these blocks and turn them into CSS elements. Next, I measure out the blocks of content or graphics in the designer’s comp and record measurements for my style sheet.” [ Michael Angeles ]
  • “You can use the grid like a wireframe (page schematic) by selecting areas of content and blocking them out, labeling them as you go.” [ Michael Angeles ]
  • “Basic Outline for Grid-based Design: Content, Audience, Illustrations / Photography / Icons, Format, Typography.” [ Feeling your way around grids ]

Articles about Grid-based Design Approach

  • Columns & Grids Dave Shea talks about the difficulty of grid systems in web pages and the compromise of columns.
    A wireframe of a grid-based design by Dave Shea
  • Subtraction: Oh Yeeaahh! - "Grids Are Good" Download the "Grids are Good" presentation (8 MB PDF) created by Khoi Vinh and Mark Boulton. Layers Cake.
  • Compose to a Vertical Rhythm On the Web, vertical rhythm – the spacing and arrangement of text as the reader descends the page – is contributed to by three factors: font size, line height and margin or padding. All of these factors must calculated with care in order that the rhythm is maintained.
  • Design grids for Web pages No one design grid system is appropriate for all Web pages. Your first step is to establish a basic layout grid. With this graphic "backbone" you can determine how the major blocks of type and illustrations will regularly occur in your pages and set the placement and style guidelines for major screen titles, subtitles, and navigation links or buttons.
  • Developing the grid that supports your design Just a few months ago when I created any design, I didn’t practice a grid system. I didn’t know much about it so I thought that I can live without it. Yes it’s true. You can live without a grid system, but should you? Why is the grid important? I will try to answer to all of your questions in this article.
  • Grid-Based Design Few basic rules and techniques in grid-based design.
    Bottom end of an example of a grid wireframe
  • Typographic Grids Grids, Ratios and Typography. Theories, such as the golden ratio (also known as the golden mean, golden number, golden section, golden proportion, divine proportion and section aurea) arise from natural patterns and they are applied in the visual and creative fields to create "beauty" by way of considered composition. The Golden Section is derived from a naturally occurring number, called Phi (1.618), which has intrigued humanity for thousands of years.
  • The Grid: The Structure of Design Using a grid is one of those basic design principles. Most news designers are working with a grid someone else designed. No matter what you think about it, you need to understand how to use it. And, at some point in your career you will likely be called upon to create a grid for a new section, or to do a re-design for a paper.
  • Cutting and sewing grid-based design: Part 1,working with other people's comps "In this article I'm going to discuss the steps I take when measuring and cutting a comp layed over a grid and turning that data into CSS. The point is to demonstrate the steps to site developers who are new to grids."
    A grid wireframe with text added to describe the different parts in it
  • The Principles of Design We can group all of the basic tenets of design into two categories: principles and elements. For this article, the principles of design are the overarching truths of the profession. They represent the basic assumptions of the world that guide the design practice, and affect the arrangement of objects within a composition.
  • Grid-based design: Designing blog theme templates The previous grid article dealt with how to come up with a CSS strategy when you're working with another visual designer's comps. Now I'd like to discuss doing grid-based theme design for open source content management systems, e.g. Drupal and WordPress....
  • Feeling your way around grids Designing grids carefully and thoughtfully, using simple compositional theory, such as the Rule of Thirds or the Golden Section, increases the legibility of your designs. By using a grid a designer shows an understanding of systems within visual communication and a sympathetic knowledge of conventions.
    Screenshot of an article about the West End of London
  • Grid-based Layout A grid is a technique that comes from print design but easily be applied to web design as well. In its strictest form a grid is literally a grid of X by Y pixels. The elements on the page are then placed on the cell border lines and overall aligned on horizontal and vertical lines.
    Screenshot of a grid overlay on the Audi Website
  • Grid Computing… and Design A look at the layout grid behind the Subtraction's 7.0 redesign.
  • Adobe Web Tech Curriculum - Page Layout Grids Introduction to Layout Grids. On each page layout grid, you'll want to decide placements for main content, branding or logo, page title, global and local navigation elements, copyright or contact information, etc.
  • Setting Type on the Web to a Baseline Grid We web designers get excited about the littlest things. Our friends in the print world must get a kick out of watching us talk about finally being able to achieve layouts on the web that they’ve taken for granted for years. Let’s face it: it’s easier these days to embed a video on the web than it is to set type consistently or align elements to a universal grid....A List Apart Article by Wilson Miner
  • The Funniest Grid You Ever Saw An in-depth look at the complicated layout grid behind The Onion.
    Screenshot of the The Onion homepage
  • Using a Background Image Grid to Lay Out Your Web Site "Simply put, you apply the grid to the body of your page as a background image so that it displays behind your site. Thus you can use it to precisely line up your layout." Article by Christian Watson.
  • Why use a grid? Grid design is a fundamental skill of any designer. Understanding proportional relationships, white space and composition are all vital in constructing a grid for any delivery platform - web, print & real 3d environments.
  • Wikipedia: Grid (page layout) A typographic grid is a two-dimensional structure made up of a series of intersecting vertical and horizontal axis used to structure content. The grid serves as an armature on which a designer can organize text and images in a rationalist, easy to absorb manner....
  • Thinking Outside the Grid “There is a new kid on the block, and her name is ‘I’ve never designed with a table in my career.’” An article by Molly E. Holzschlag
    Boxes creating a grid
  • Grids: Show 'em if you got 'em Grids are a topic that’s rarely discussed or disected in the online community, yet is one of the fundamental components of good design. Why is it that many designers have a hard time with the grid?
  • Grid systems in Web Design An overview of grid-based techniques. Every design you make should have a clear grid system whether its print or for the web because they help to organise information into a clear easy to follow layout. Here we roundup the best articles and resources on the subject.

Tutorials

  • Five simple steps to designing grid systems - Preface In the context of graphic design, a grid is an instrument for ordering graphical elements of text and images. The grid is a child of Constructivist art and came into being through the same thought processes that gave rise to that art movement.
  • Five simple steps to designing grid systems - Part 1 The first part of this Five Simple Steps series is taking some of the points discussed in the preface and putting it to practice.
  • Five simple steps to designing grid systems - Part 2 In part one of this Simple Steps series I talked about how to use a simple ratio, that of the paper size you are using, to create a symmetrical grid on which to create your designs. This, the second part in the series, will deal with other ratios and how they can be combined to create more complex grid systems.
    Screenshot of a grid wireframe
  • Five simple steps to designing grid systems - Part 3 The third installment to this series is going to be a little different. The previous installments have been talking through some of the basics of grid construction using ratios as the primary device.
  • Five simple steps to designing grid systems - Part 4 For the purposes of this article, I'm going to be focussing on the theory of creating the grid rather than the implementation. I did mention in the last series that I would cover implementation using CSS, well I'm not going to.
    Grid overlay of the BBC website
  • Five simple steps to designing grid systems - Part 5 Flexible vs Fixed. Which one to choose? Why choose one over the other? Well you won't find the answers to those questions here. What I'm aiming to do with this article is to investigate how the theory of grid design can be applied to a flexible web page.
  • Grids make eyes happy: how to use Grids An example on how to create effective grid systems.
  • Grids: Order Out of Chaos Invisible Structures: When and Why to Use Grids in Page Layout. Many of the pages that you see everyday have a grid. You may not see it but it is there, holding up the design, establishing structure, guiding the page elements.
  • Designing Grid Systems for Flash I’ve decided that I’m going to write a little something up for those people interested in grids. I’m going to walk you through the process of creating a grid for a Flash based site that will work for screen resolutions of 1024×768 and up.
  • How to Create Page Layouts in GoLive CS2 GoLive CSS-based or table-based layout grids enable you to create designs by freely positioning objects anywhere on the page. You can convert a CSS-based layout grid to a table-based layout grid. You can also convert a table-based layout grid to an HTML table.

Useful Tools for Grid-based Designs

  • Adaptive Grid System based on the Golden Section The Columns are defined using em to keep line length consistent and varying text size using javascript to make the web page fill the browser window.
  • Layout Grid Bookmarklet Inspired by Khoi Vinh’s post about using a background image of a grid for layout, and a subsequent post over at Smiley Cat about the same thing, I decided to knock up a quick Photoshop style Layout Grid Bookmarklet....
  • Grid Overlay Bookmarklet Just a quick note to share my version of Andy Budd’s Layout Grid Bookmarklet.
  • WPDFD Browser Grid This grid represents the maximum safe sizes for the three main monitor sizes in use today (June 2001). It takes into account such things as browser menubars and scrollbars and assumes that the browser window has been maximised. 640 x 480, 800 x 600, 1024 x 768
  • Free Online Graph Paper / Grid Paper PDFs Downloadable and very printable
  • Gridding the 960 Background image grid + pixel ruler + column divisions for 960px-width layout, all in one mean little package.
    A chart in a grid layout
  • Web Page Layout Grid Add this image as a background to the body of your page to help you lay it out.
  • Position is Everything - Vertical Grids A method enabling the vertical positioning of elements across grids/columns
  • CSS Grid Calculator Use the CSS Grid Calculator to quickly visualize page layout and draw grids in a variety of ways. It provides accurate visual feedback on how text blocks and page divisions will appear within a browser window, and returns style declarations for divisions and text to copy and paste into style sheets.
  • TypoGridder To get to the heart of it: a baseline grid is added. You initialize the TypoGridder and it automatically gets the lineheight of an element (by default p, but you can choose any jQuery selector). Then it queries a little PHP script which creates a very simple image which is used for tiling. The result is an opaque layer with a tiling baseline grid.
  • Grid Ruler A simple image that can be applied as the background to most block level elements that will help you get an idea what's going on between browsers and platforms without the need for another application.
    Screenshot of an image of a ruler accompanied by some text
  • YUI: CSS Grid Builder A simple interface for Grids customization.
  • YUI Grids CSS The foundational YUI Grids CSS file offers three preset page widths, seven core templates, and the ability to nest subdivided regions of one to four columns..
  • How to play with Yahoo Grids CSS Yahoo released their Yahoo! User Interface. One part of which is their webpage templates, the Grids CSS. To follow along you will need to download the YUI library, a working test Drupal install and a text editor of some sort.
  • Page Grids Successful web page design often leverages methods rooted in print design by utilizing an underlying grid system. First, establish a grid, or system of grids, that take into account advertising needs, dynamic elements, etc. Next, create templates and code to support designers and developers..
  • Hacking Technique: Yahoo's Grid System (Part 1) "And what Yahoo! UI CSS Grid has to do with us? Well, I tried to integrate Yahoo! Grid into Blogger Beta, and the result was sweet. By injecting some additional CSS code and some div tags into the simplified version of the Beta template, one can rearrange one's layout without any CSS knowledge. This article will show you how to do that."
  • Hacking Technique: Yahoo's Grid System (Part 2) In this post, I get into some technical details, and it also serves as a note for myself in finding interesting things about the Yahoo! CSS Grid system. Read on if you curious on how 3, 4, or 5 columns can be achieved.
  • OS3Grid - Grid for Web Sites OS3Grid a JavaScript component allowing you to create and use powerful grids in your web sites. As you can see from the Examples OS3Grid is both flexible and powerful, with a rich set of features and an easy to use API for the developer.
  • “Grid Systems in Graphic Design” by Josef Muller-Brockmann
  • “Geometry of Design: Studies in Proportion and Composition” by Kimberly Elam
  • “Grids for the Internet and Other Digital Media” by Veruschka Gotz
  • “Geometry of Design” by Kimberly Elan
  • “The Elements of Typographic Style” by Robert Bringhurst
  • “Making and Breaking the Grid: A Graphic Design Layout Workshop” by Timothy Samara

Wednesday, July 22, 2026

When It Makes Sense To “Block” The Main Thread

 

The common rule of thumb is to never “block” the browser’s main thread when running JavaScript tasks. But is this a hard rule? \ describes a use case he encountered involving a screenshot extension where he made an exception to the rule and decided that blocking the main thread was absolutely the right thing to do.

We’ve all heard of the sacred rule in modern web development, the rule never to be broken. The rule of “Never block the main thread.”

You almost can’t miss it as a web developer; it’s in almost every performance guide, and to be fair, it is good advice. We all know the browser’s main thread is single-threaded, meaning it can only do one thing at a time.

Plus, as we know, the main thread isn’t ours alone; we share it with the browser’s rendering engine, input handlers, and other critical tasks. As a result, the less time we hold onto the main thread, the more responsive an app feels. That leads us to share tasks with background workers as we’ve convinced ourselves there should be a hard line between the UI and any computation, and that line shouldn’t be crossed.

And that is what a “recommended” architecture looks like.

But I dare say that *sometimes*, moving the data to a worker is slower than just letting the main thread do the work.

I found this out a few months ago while building a Chrome extension with screenshotting features called Fastary. I kept finding a latency of about 2 to 3 seconds in all my testing, even after using an Offscreen Document (a background process in Chrome extensions) to handle the canvas operations. A screenshot task should feel instant without lag, after all.

It is quite ironic that by reflex, we move work away from the main thread to avoid freezing the UI, but sometimes the act of moving that work (e.g., serializing, copying, and deserializing) can also freeze the UI. And sometimes the recommended approach of letting the background do the work can be slower than just doing the work on the main thread.

Let’s talk about that.

The Architecture Of Browser Context Isolation

To put things in perspective, let’s understand why we isolate browser contexts and how they communicate with each other, with emphasis on the communication part.

A browser is more than a single environment. Different environments are running at the same time, each having its own memory space, what it can access, and rules:

  • The main thread is what we are most familiar with; this is where JavaScript logic runs, where the DOM lives, where styles get rendered, and where users interact.
  • The Web Workers are separate threads that can also execute JavaScript without DOM access. We mostly use this for heavy data tasks.
  • The Service Workers are network-related proxies in charge of intercepting network requests and can even run when the page is closed.
  • And then there are Chrome extension contexts, where we have background service workers, content scripts, and Offscreen Documents (the relevant ones for this article).

Each one of these is isolated from the others. A web worker or background script lives in a different memory space from the main thread. They cannot just reach and read each other’s variables or logic, and this is known as the “shared-nothing” architecture.

How do these isolated environments communicate? They explicitly message each other back and forth using APIs, like postMessage().

The Structured Clone Algorithm

postMessage() tells the browser to take a piece of data and deliver it to the context that requested it. But to do this, the browser relies on the Structured Clone Algorithm (SCA).

You’re probably familiar with JSON.stringify(). SCA is similar, but much stronger and smarter. In its simplest form, SCA is a deep, recursive copy operation, i.e., cloning. It walks through the entire data structure it is given, clones every single value, serializes it into a transportable format, ships those bytes to the target contexts, and then reconstructs the original object on the receiving side.

SCA is fast, or maybe fast-ish… For a small regular config object like {theme: "dark"}, it is imperceptible; you don’t even notice it. The story changes, however, when dealing with heavy data because the SCA is a synchronous blocking O(n) operation, i.e., the cost increases linearly with the size of your data.

Let’s put that into perspective. A user clicks a button, and internally, an 8MB image payload is sent to a background worker for processing. When you call postMessage(), the main thread must immediately stop what it is doing to run this serialization and copying process.

So, if the time it takes to pack, ship, unpack the data, and go back to the start is longer than the time to just process the data on the main thread, why not do that instead?

What About Transferable Objects?

I’m sure some of you are already thinking, “Why not just use Transferable objects?” And that is a valid point. Let’s talk about that.

Developers who really pursue ultra-high-performance web apps usually use Transferable objects (e.g., ArrayBuffer, ImageBitmap, or MessagePort) to bypass the Structured Clone Algorithm. This is because when you transfer an object, you’re not making a copy (like SCM). Instead, the browser switches ownership of the data from one context to another.

The browser performs a hand-off whereby the sending context loses access to the data instantly, and the receiving context takes full control. It is actually insanely fast. According to Chrome Developers’ benchmark, transferring a massive 32MB ArrayBuffer can take under 7ms, compared to about 300ms when cloning with SCM. That’s a 43x speed boost.

Structured cloning vs. Transferable Objects by Chrome Developers
Structured cloning vs. Transferable Objects by Chrome Developers. (Image source: Chrome for Developers) (Large preview)

But like all good things, there are downsides. To name a few:

  • You lose it once you send it.
    If the UI still needs that data (like to show an image preview), you can’t access it anymore.
  • Not all data is transferable.
    A plain JS object is not. A Blob is not. Even a Base64 string is not.
  • API limitations.
    In the context of browser extensions, Chrome’s internal messaging (chrome.runtime.sendMessage) traditionally forces everything through JSON serialization.

So, as far as my screenshot extension went, Transferable objects were not an option.

Why We Isolate Contexts Anyway

Why do we even bother isolating contexts at all? Why not just leave it all to the main thread?

Offloading long-running CPU tasks to a background thread is absolutely the right thing to do. The browser needs to paint a new frame every 16.6ms to keep things fluid; that means any task that takes >50ms is generally considered “long”. Offloading to the background is absolutely the right thing to do.

The issue, however, is that we’ve turned this “never block the main thread” into an absolute rule, without asking is this task expensive to process or expensive to move?

I have come to realize now that the rule is less “never block the main thread” than “never block the main thread for too long.”

“

When The Right Architecture Is The Wrong Architecture

My goal with the Fastary extension was to make it feel like a native app, running as smoothly and instantly as you would expect a native app to.

As you already know, I took the recommended approach to use the Offscreen Document to handle DOM work in the background. But to my surprise, that took a different turn.

The Offscreen Document API is a clear winner. You create a hidden, undisplayed document that runs entirely in the background. It has a DOM and supports Canvas. For example, if I want to crop a screenshot, stitch multiple screenshots together, perform heavy image manipulation, or add a watermark, Offscreen Document was made for that.

Turns out that was not the best approach. This was my architecture:

  1. The background Service Worker captures a screenshot with chrome.tabs.captureVisibleTab(), which returns a Base64-encoded data URL string.
  2. The background Service Worker uses chrome.runtime.sendMessage() to ship this image payload to the Offscreen Document.
  3. The Offscreen Document receives the image, loads it into an <img> element, then draws it onto a canvas before it applies the user’s crop coordinates, encodes the result, and sends the processed image back to the background worker.

But when I tested it, the screenshot didn’t feel instant. As I said earlier, there was a consistent 2–3 second lag.

I figured out that when captureVisibleTab() takes a screenshot, it returns a Base64 URL string, and on a standard 1080p screen, that string could be approximately 1MB or more, depending on how detailed the image is. It gets even more interesting on modern Retina displays (e.g., MacBooks) as they tend to automatically double the image’s size by default.

Keep in mind that since the image payload could be doubled and extension messaging relies on JSON serialization (as of this writing), we potentially deal with massive synchronous communication that costs an entire round trip.

The image string data is JSON-serialized at least twice: once when going into the Offscreen Document and once coming back out with the processed results to the background worker. The actual image processing (cropping) done inside the Offscreen Document was fast, no doubt, but I can’t say the same about the transfer overhead.

The Retina High-DPI Problem

As if the latency itself wasn’t enough, I noticed a rather subtle bug — which, now that I think of it, was more of my ignorance. After a screenshot was taken, the crop result was completely off in a way that either weirdly scaled the image or resulted in incorrect coordinates.

It turns out that when a user selects a region to crop, the content script gets the box coordinates using getBoundingClientRect(), which is measured in CSS pixels; this is what the DOM uses. But when the screenshot is captured natively in Chrome, the browser doesn’t crop it automatically; it instead uses the physical hardware pixels to get the full screen capture. And the browser uses devicePixelRatio (DPR) to know how many physical pixels should represent one CSS pixel. Basically, if a user on a Retinal display (DPR = 2) highlights an area of 400x300 CSS pixels, the actual captured image area is 800x600 physical pixels.

Note: One CSS pixel is equal to 1 physical pixel (DPR of 1) on a standard monitor. On a Mac Retina display or a modern 4K monitor, however, the DPR is usually 2 or 3.

For an accurate crop, I needed to apply these two different measurement systems with the right DPR, i.e., scale the crop coordinates by the DPR. But remember, Offscreen Documents have no physical display. Processing any image would have a default DPR equal to 1. To fix this, I would have to capture the exact devicePixelRatio from the active tab, serialize it, pass it alongside the image payload, and manually do the scaling math inside the Offscreen Document. The complexity starts to compound.

What if I broke the golden rule and did the work on the main thread instead?

Working On The Main Thread

Some developers will argue that UI tasks are the only things that should run on the main thread, but I don’t fully agree with that. Personally, I believe that user explicitly-invoked actions that need immediate results can sometimes get a solid pass to run on the main thread, provided the work is incredibly fast (e.g., 1s).

That’s what I did: scrap out the Offscreen Document and reengineer the logic. Instead of:

Background → [serialize] → Offscreen Document → [serialize] → Background → Content Script

…I decided to run the whole image processing in the active tab:

  1. The background Service Worker captures the screen and gets the Base64 string (same as before).
  2. The background sends the payload directly to the content script in the active tab using chrome.scripting.executeScript().
  3. The content script (running on the main thread) receives the payload, draws it to a canvas, performs the crop using the correct DPR value, and copies the result to the clipboard.
// Background Script
const screenshotUrl = await chrome.tabs.captureVisibleTab(undefined, { format: "png" });

// Inject the processing function into the active tab as a content script
await chrome.scripting.executeScript({
  target: { tabId: activeTab.id },
  func: processAndCopyImage,
  args: [{ base64Image: screenshotUrl, cropData: userSelection }]
});

This approach completely clears out multiple context hops and round trips that JSON serialization requires. The only cross-context transfer involves sending the data URL from the background to the content script.

The Retina DPI issue essentially solved itself, as the content script runs directly inside the real, active browser tab because it knows the monitor’s real devicePixelRatio.

But there’s an elephant in the room that you may have noticed.

Sure, the image is now processed on the main thread, and the background manipulates the canvas in the active tab. I could technically be blocking the main thread. That’s where I amended the “no blocking the main thread” rule to “no blocking the main thread for too long.” In this specific case, at least, blocking the main thread for a task the user requests for approximately one second is justifiable. It works conversely as well: maybe don’t isolate processes if the data transfer cost is greater than the processing cost.