惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
IT之家
IT之家
J
Java Code Geeks
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
W
WeLiveSecurity
B
Blog RSS Feed
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security @ Cisco Blogs
博客园 - 叶小钗
月光博客
月光博客
Webroot Blog
Webroot Blog
H
Hacker News: Front Page
N
News and Events Feed by Topic
P
Proofpoint News Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Help Net Security
Help Net Security
S
Secure Thoughts
SecWiki News
SecWiki News
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
S
Schneier on Security
A
Arctic Wolf
博客园 - 司徒正美
T
Tor Project blog
T
Tenable Blog
量子位
D
DataBreaches.Net
PCI Perspectives
PCI Perspectives
T
The Exploit Database - CXSecurity.com
T
Threatpost
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
Cloudbric
Cloudbric
T
The Blog of Author Tim Ferriss
N
News | PayPal Newsroom
Project Zero
Project Zero
S
Securelist
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
L
LINUX DO - 热门话题
Security Archives - TechRepublic
Security Archives - TechRepublic
O
OpenAI News
C
Cisco Blogs
V
V2EX
P
Privacy & Cybersecurity Law Blog
Cisco Talos Blog
Cisco Talos Blog

CSS Wizardry

Front-End’s Missing Metric: The TBT Window Meet Your Users Where They Are with Obs.js Better Browser Caching with No-Vary-Search font-family Doesn’t Fall Back the Way You Think What Is CSS Containment and How Can I Use It? When All You Can Do Is All or Nothing, Do Nothing Obs.js: Context-Aware Web Performance for Everyone Low- and Mid-Tier Mobile for the Real World (2025) The Fastest Site in the Tour de France Making Sense of the Performance Extensibility API Why Do We Have a Cache-Control Request Header? HTML Is Not a Programming Language… Build for the Web, Build on the Web, Build with the Web Licensing Code on CSS Wizardry A Layered Approach to Speculation Rules Designing (and Evolving) a New Web Performance Score Core Web Vitals Colours The Ultimate Contract Templates for Tech Consultants: Protect Your Business and Get Paid Optimising for High Latency Environments Cache Grab: How Much Are You Leaving on the Table? blocking=render: Why would you do that?! Correctly Configure (Pre) Connections The Three Cs: 🤝 Concatenate, 🗜️ Compress, 🗳️ Cache What Is the Maximum max-age? How to Clear Cache and Cookies on a Customer’s Device The Ultimate Low-Quality Image Placeholder Technique Core Web Vitals for Search Engine Optimisation: What Do We Need to Know? The HTTP/1-liness of HTTP/2 In Defence of DOM­Content­Loaded Site-Speed Topography Remapped Why Not document.write()? Speeding Up Async Snippets Critical CSS? Not So Fast! Measure What You Impact, Not What You Influence Optimising Largest Contentful Paint Measuring Web Performance in Mobile Safari Site-Speed Topography Speed Up Google Fonts Real-World Effectiveness of Brotli Performance Budgets, Pragmatically Lazy Pre-Browsing with Prefetch Making Cloud.typography Fast(er) Time to First Byte: What It Is and How to Improve It Self-Host Your Static Assets Tips for Technical Interviews Cache-Control for Civilians Bandwidth or Latency: When to Optimise for Which ITCSS × Skillshare What If? CSS and Network Performance The Three Types of Performance Testing Getting to Know a Legacy Codebase Image Inconsistencies: How and When Browsers Download Images Identifying, Auditing, and Discussing Third Parties My Digital Music Setup Measuring the Hard-to-Measure Finding Dead CSS The Fallacies of Distributed Computing (Applied to Front-End Performance) Ten Years Old Relative Requirements Airplanes and Ashtrays Performance and Resilience: Stress-Testing Third Parties Refactoring Tunnels Little Things I Like to Do with Git Writing Tidy Code Configuring Git and Vim Base64 Encoding & Performance, Part 2: Gathering Data Base64 Encoding & Performance, Part 1: What’s Up with Base64? Code Smells in CSS Revisited Typography for Developers Moving CSS Wizardry onto HTTPS and HTTP/2 Ack for CSS Developers A New Year, a New Focus Preparing Vim for Apple’s Touch Bar Choosing the Correct Average CSS Shorthand Syntax Considered an Anti-Pattern CSS Wizardry Newsletter Nesting Your BEM? Improving Perceived Performance with Multiple Background Images Continue Normalising Your CSS Pure CSS Content Filter Pragmatic, Practical, and Progressive Theming with Custom Properties Refactoring CSS: The Three I’s Speaker’s Checklist: Before and After Your Talk Improving Your CSS with Parker The Importance of !important: Forcing Immutability in CSS Mixins Better for Performance Managing Typography on Large Apps White October Events Workshop Partnership BEMIT: Taking the BEM Naming Convention a Step Further Travelling Like You Want to, When You Have To Contextual Styling: UI Components, Nesting, and Implementation Detail Subtleties with Self-Chained Classes Cyclomatic Complexity: Logic in CSS Immutable CSS Can CSS Be Too Modular? More Transparent UI Code with Namespaces When to use @extend; when to use a mixin The Specificity Graph CSS Wizardry Ltd.: Year 1 in review
Building better grid systems
Harry Roberts · 2011-08-24 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. The problem
  2. The current solution(s)
    1. The other current solution
  3. The solution
  4. Roll your own…

With every grid system that gets released—and there are a lot now—I notice the same issue with nigh on every one of them; handling the extra margin/gutter on the last <div>.

N.B. This post is about the HTML and CSS that powers grid systems, rather than the columns, construct, system and layout itself.

The problem

If you have a grid system where each grid module is defined with a class of, say, .grid, you might have some CSS like this:

.row{
    width:940px;
    overflow:hidden; <span class="code-comment">/* This is just for brevity. Please use a better clearfix: http://nicolasgallagher.com/micro-clearfix-hack/ */</span>
    clear:both;
}

.grid{
    float:left;
    margin-right:20px;
}

...

.col-4{
    width:220px;
}

...

The most important thing to note is that every .grid has a margin-right of 20px, so—in a 16 column 940px grid system—4 × .col-4 actually equals 960px (4 × (220px + 20px)). This is 20px (or one margin) bigger than your wrapper.

The formula for a complete system is:

f = n(c) + n-1(g)

Where:

  • f = full row
  • n = number
  • c = columns
  • g = gutters

Basically, a full row comprises of n columns and n-1 gutters; we want one less gutter than we have columns. We need to lose a gutter somehow.

The current solution(s)

The simplest and most common solution is to use a class of .last or .end on the last or end grid column to remove its margin:

This would give us:

<div class="row">

  <div class="grid  col-4">
    <p>One box plus one gutter</p>
  </div>

  <div class="grid  col-4">
    <p>One box plus one gutter</p>
  </div>

  <div class="grid  col-4">
    <p>One box plus one gutter</p>
  </div>

  <div class="grid col-4  end">
    <p>One box only</p>
  </div>

</div>

This solves the problem, but it means the developer has to remember to add that class every time they construct a row of grids.

Another problem is that if a programmer needs to dynamically display, say, a series of images in a grid system, they need to do some scripting to say ‘if this is the x column then add a class of .end’. Not a massive overhead, but an overhead nonetheless.

The other current solution

Another solution I’ve seen recently is used on Twitter’s Bootstrap framework and a few other places. This solution is a little more elegant, but still not very robust.

It works by removing the margin-right:20px; from .grid and applying it as a margin-left instead. Then—using the dynamic :first-child pseudo-selector (:first-child is used as it has better browser support than :last-child)—you can target the first div in a row and remove its margin, thus:

.grid:first-child{
  margin:0;
}

This keeps your markup clean as you don’t have to include the special class and also means your devs don’t have to take the extra class into consideration, However, this is not without its own problems…

The smallest problem with using this method is that the :first-child selector is quite an inefficient one, but selector performance is another post for another time.

The most significant drawback is that :first-child only ever matches one grid in the row, meaning you can’t have multiple-row grid constructions. Take the following (crude) representations…

  • Tildes (~) and broken bars (¦) denote the .row div
  • Hyphens (-) and pipes ( ) denote .grid divs
  • x denotes :first-child
  • ! denotes borked

:first-child works out fine here as we only have a one-row-deep layout. The first div is the only flush-left div:

+~~~~~~~~~~~~~~~~~~~~~~~~~+
¦ +---+ +---+ +---+ +---+ ¦
¦ | x | |   | |   | |   | ¦
¦ +---+ +---+ +---+ +---+ ¦
+~~~~~~~~~~~~~~~~~~~~~~~~~+

In this following example however, :first-child will not work as intended as there are two flush-left divs but only one of them is the first child. This is where this method breaks, and more-than-one-row-deep layouts are not uncommon:

+~~~~~~~~~~~~~~~~~~~~~~~~~+
¦ +---+ +---+ +---+ +---+ ¦
¦ | x | |   | |   | |   | ¦
¦ +---+ +---+ +---+ +---+ ¦
¦ +---+ +---+ +---+ +---+ ¦
¦ | ! | | ! | | ! | | ! | ¦
¦ +---+ +---+ +---+ +---+ ¦
+~~~~~~~~~~~~~~~~~~~~~~~~~+

So :first-child kinda works, but not well enough. The solution…?

The solution

In short, the solution is to not remove that extra margin, but to hide the effects of it.

Essentially the real problem is that the combined width of a full row is one gutter wider than our container, right? Well what we need to do is make our container one gutter wider but disguise the extra width by using a negative margin equal to one gutter.

This can be a bit of a headf**k so bear with me. What we need to do is apply the gutter as a margin-left on the .grid, as Twitter do, but we’re not going to remove any of them. No pseudo-classes, no special classes, nothing. It’s gonna stay there.

We can hide the effects/breakage caused by the extra gutter by giving the container .row a width of all the columns and gutters combined and then a negative margin-left equal to one gutter to pull everything back across again, soaking up the effects of the margin-left.

Our 940px .row now becomes 960px wide to allow for the fact we are no longer removing the end gutter, then we pull it all back over by 20px to remove the visual effects of that extra width, thus:

.row{
  width:960px;
  margin-left:-20px;
  overflow:hidden;
  clear:both;
}

.grid{
  float:left;
  margin-left:20px;
}

...

.col-4{
  width:220px;
}

...

This way we can have multiple-row constructions and never have to remember the special .end/.last classes.

To see this technique in action head on over to inuit.css and poke about the page’s grid system using Firebug or similar. It’s most apparent in the list of features…

Roll your own…

To transfer this technique, you only need to know three things:

  • The number of columns in your grid system
  • The width of one column
  • The width of one gutter

With these, your formula is simply:

.row{
  width: (number of columns * width of one column) + (number of columns * width of one gutter) px;
  margin-left: -width of one gutter px;
  overflow:hidden;
  clear:both;
}

.grid{
  float:left;
  margin-left: width of one gutter px;
}

So let’s create one using 12 columns that are 50px wide with a gutter of 25px:

.row{
  width:900px;
  margin-left:-25px;
  overflow:hidden;
  clear:both;
}

.grid{
  float:left;
  margin-left:25px;
}

Plugging in our numbers gives us a grid system that doesn’t require special classes, is totally flexible (you can move columns without needing to move a class around), and gives you more varied layouts (multiple rows).

I employ this technique on both inuit.css and Fluid Grids and it’s proved perfect so far. Robust, portable and lean.