Posts in the Tech Category

“CSS: The Definitive Guide, 4th Edition” Release and Contents

Published 7 years, 1 month past

CSS: The Definitive Guide, 4th Edition is wending its way to the reading public, and I have some updates on that.

The O’Reilly catalog still says October 2017, but for the physical copy, Barnes & Noble and Amazon are now listing a release date of November 5th, 2017, so we seem to have just missed that October release window I was hoping to hit.  But not by much!  The DRM-free version at eBooks is apparently available now, as are Nook and Kindle versions.

For those of you with access to O’Reilly’s Safari subscription service, there’s an older version of the book currently available.  Apparently, so many people have joined the queue to get it that the content-update process breaks.  (Our production editor was impressed.)  O’Reilly’s engineering staff is aware of the problem and working on it, so hopefully by the time you read this, the problem will be resolved and the final copy online.  If not, our apologies, and thanks for your patience.

If you’re wondering if this edition is for you, absolutely it is!  But I would say that, wouldn’t I?  As would my co-author Estelle.  To help you decide, here’s the Table of Contents with a few brief notes on the new things contained therein (chapters marked ALL NEW! are chapters that didn’t exist at all in the 3rd Edition):

  1. CSS and Documents – a brief overview of what CSS is for, how to apply it (including via HTTP headers!), basic syntax, media and feature queries
  2. Selectors – all the selectors as of mid-2017, including :not(), validity pseudo-classes, the case-insensitivity modifier in attribute selectors, and more
  3. Specificity and the Cascade – probably the least-changed chapter, this lays out the cascade in some detail
  4. Values and Units – adds viewport units, ch (which does not actually mean “one character”), calc(), and various new color syntaxes like HSL and #RRGGBBAA patterns
  5. Fonts – includes a lot about @font-face and the process of loading custom fonts, in addition to the classics like weight, style, variant, family, etc.
  6. Text Properties – adds a fair amount of material on non-horizontal writing and alignment, writing modes, hyphenation, and so forth
  7. Basic Visual Formatting – this is another chapter that didn’t change a huge amount from the 3rd Edition, though it does touch on the new values for display
  8. Padding, Borders, Outlines, and Margins – to all the existing details on those basic topics, we’ve added border-radius and all the properties that affect image borders
  9. Colors, Backgrounds, and Gradients – there are all the new background-related properties like background-size and background-clip, handling multiple background images, and the wonder world of linear and radial gradients, explained in more detail than anyone probably thought reasonable, plus there’s a section on box-shadow
  10. Floating and Shapes – floating hasn’t changed much, but the section on Float Shapes is all new and pretty nifty, if I do say so myself
  11. Positioning – this got a section on sticky positioning to go along with the classic positioning material
  12. Flexible Box Layout – ALL NEW! – the ins and outs, the nitty-gritty, the pros and cons of Flexbox
  13. Grid Layout – ALL NEW! – Grid is here and it’s hot; this chapter explores it in up-to-the-minute detail
  14. Table Layout in CSS – the third of the minimally-updated chapters, this discusses how data tables are laid out
  15. Lists and Generated Content – a surprisingly large amount of new material in this chapter, pretty much all centered around @counter-style and its capabilities and how you can create emoji counting systems
  16. Transforms – ALL NEW! – rotating, scaling, translating, 3D effects, and more, all with a minimum of matrix math
  17. Transitions – ALL NEW! – state-based animations and how to define them, introducing some of the basic animation concepts along the way
  18. Animation – ALL NEW! – stateless animations, which can happen at any time, for any reason you choose to define, made possible through @keyframes and a bevy of new properties
  19. Blending, Filtering, Compositing, and Masking – ALL NEW! – all (okay, almost all) the nifty things you used to do in Photoshop, now available natively in browsers, so you can do grayscale images that pop color on hover or click without having to produce two separate images
  20. Media-Dependent Styles – this was almost ALL NEW!, but it’s a radically reworked chapter from the 3rd Edition with fewer bits about printing, no bits on audio, and a whole lot of details about media queries

And then the Appendices:

  1. Animatable Properties – a list of CSS2.1 properties that are animatable, with a note on exactly what can be animated
  2. Basic Property Reference – a compact table of properties, their default values, and the complete value syntax
  3. Color Equivalence Table – the 148 color names defined in CSS Color Level 4 with their equivalents in RGB decimal, RGB percentage, HSL, and hexadecimal formats

Whew!  After all that, you might be thinking that, much like Emacs, this book has everything.  And I’d like to say that it does, but… it doesn’t.  For example, I decided fairly late in the process to drop multicolumn properties.  It was a tough decision, but when I started testing browser support and looking at the state of the specification, it felt too unstable to include.  I’ve rushed explanations in past editions, and usually regretted it.  (Although, fun fact: the 2nd Edition contains the only known documentation of the CSS Working Group’s multi-hour discussion on how the old clip property was supposed to work.)  So I put multicolumn off for the next edition.

Still, there are far far far more examples of things added in than things left out, enough to make this edition twice as long as the previous.  There’s been a lot of growth in CSS over the past decade, and I think Estelle and I have brought together something that will get you up to speed on very nearly all of it.  For those of you eagerly waiting on a copy, we really hope you enjoy the result!


“CSS: The Definitive Guide, 4th Edition” Goes to Print

Published 7 years, 1 month past

Yesterday afternoon, CSS: The Definitive Guide, 4th Edition went to the printers.  Eighteen years after the First Edition hit shelves, eleven years after its predecessor came out, five years after I first started working on this edition, and thanks in no small part to Estelle Weyl and a parade of long-suffering editors at O’Reilly, the last changes were entered, the pages were locked, and the repository closed.

It comes in at 1,088 pages: almost exactly twice the length of the Third Edition, with six new chapters and a lot of overhauling of old chapters.  Flexbox, Grid, filtering, blending, clipping and masking, float shapes, animations and transitions, transforms, image borders, counting systems, custom properties (a.k.a. CSS variables), media and feature queries — they’re all in there, and a whole lot more besides.  Gradients got a major new section in what used to be called just “Colors and Backgrounds” and is now “Colors, Backgrounds, and Gradients”.  And all the new background properties!  So many new background properties.

We didn’t skimp on the visuals, either.  The book has, if I counted correctly, a total of 778 figures.  Almost all of them were captured in-browser, and you can download or clone all the files from GitHub.  If you’d rather just browse them online, you can do so thanks to GitHub Pages.  That’s also where to find the transition and animation examples that are referenced in the text, but not figures themselves (detailed animation being somewhat difficult to represent on paper).  If we add figures and animation examples together, there are 826 elements supporting the main text.  Which feels like a lot to me.

The book will be available in both tree-wafer and glowing-display formats from your favorite supplier of such things; e.g., Amazon.  (If you’re going to buy through Amazon and are inclined to support another aspect of my life, please designate Rebecca’s Gift as your Amazon Smile recipient before buying the book.)  I also hear tell it will be available DRM-free from eBooks.com, and potentially in PDF form for those who prefer it.  O’Reilly doesn’t sell books directly any more, but I do believe it will be avialable to those with Safari subscriptions.

I’ll have more to say about the book and its contents as the release date draws closer.  Last I heard, it should be out by the end of this month, but as always, release dates can slip for any number of reasons.  Even if this release does slip, it should still come out no later than early November.

(Let’s hope I didn’t just jinx that.)

This is always a tense and exhilarating time.  What if I got a huge piece completely wrong?  What if I made the wrong calls on what to include and what to defer to the next edition?  What if I missed egregious typos?  What if nobody likes it?  Basically, the same doubts that strike most any author.  But there’s also the incredible feeling of a project brought to its conclusion and the anticipation of getting it into readers’ hands.  This has been a longer-than-usual time coming, but as it usually does, the time has come at last.  I hope you’re looking forward to it half as much as I am.


Adding Backgrounds to Directly Loaded SVGs

Published 7 years, 4 months past

My primary SVG viewer is Firefox.  This is partly because it’s always running, so the startup time is essentially zero.  It also allows me to directly inspect and modify elements of the SVG element through the Web Inspector, which can be handy.

But I’ve run into a problem more than once, which is that if I load an SVG file in Firefox, the browser window’s background defaults to white, and a lot of times I’m trying to view images that are partially or entirely white.  I started thinking that if there were a way to make the window background medium gray, that would solve the problem with rare downsides, since I can’t remember trying to view an all-medium-gray SVG.

After a question on Twitter and some ideas from Tibor Martini, I realized I could use Stylish to give the SVG files a background through CSS.  I didn’t want to select all SVGs, only those I was loading directly, so I tried this:

svg:root {background: gray;}

And it worked!  So I decided to make it more robust by doing a multicolor gradient, and grayscaling it on hover.  I couldn’t use filter because that would grayscale the whole image, rather than just the background, but that was easy to work around.  I ended up with this:

svg:root {background: linear-gradient(135deg, hsl(0,50%,60%), hsl(180,50%,40%));}
svg:root:hover {background: linear-gradient(135deg, hsl(0,0%,60%), hsl(180,0%,40%));}

Which works great!  Except that I discovered Firefox applies it to all SVGs, even those loaded into HTML documents via img.  SVGs apparently define their own roots, which I hadn’t expected, but I can see how it might make sense.  So I poked around in MDN until I came up with this:

@-moz-document url-prefix(file:) {
    svg:root {background: linear-gradient(135deg, hsl(0,50%,60%), hsl(180,50%,40%));}
    svg:root:hover {background: linear-gradient(135deg, hsl(0,0%,60%), hsl(180,0%,40%));}
}

And that’s exactly what I wanted.  If it’s useful to you, have at it.  Just paste that into a new Stylish rule in Firefox, and you should be good to go.

If you’re on Chrome, you can import the above into Stylish and create a new rule, but it hasn’t worked for me, and I’m not sure why not.  Removing :root didn’t fix it when I tried, and that shouldn’t matter anyway: I can see in Chrome’s user styles that svg:root is used and applied.  And my Stylish toolbar icon shows the rule is being applied.  It just doesn’t do anything I can see.  If anyone can figure out how to make it work, or explain why it can’t work, I’d love to know in the comments!


CSS: The Definitive Guide, 4th Edition

Published 7 years, 4 months past

On Monday, July 3rd, as I sat in the living room of a house just a bit north of New York City, I pushed the last writing and editing changes to CSS: The Definitive Guide, Fourth Edition and notified the production department at O’Reilly that it was ready.

All twenty chapters, three appendices, and associated front matter are now in their hands.

It’s been a long and difficult journey to get here.  Back in 2011-2012, I started updating chapters and releasing them as standalone books, for those who wanted to grab specific topics early.  In mid-2013, I had to stop all work on the book, and wasn’t really able to get back into it until mid-2015.  At that point, I realized that several new chapters had to be added — for example, when I started out on this edition, Flexbox and Grid were pie-in-the-sky ideas that might or might not come to pass.  Feature queries weren’t a thing, back then.  Filters and masks and blend modes were single-browser at best, when I started out.  And forget about really complex list counters.

Now all those topics (and more!) have chapters, or at least major sections.  Had I not been delayed two years, those topics might not have made it into the fourth edition.  Instead, they’re in there, and this edition may well end up twice as long as the previous edition.

I also might not have brought on a co-author, the inestimable Estelle Weyl.  If not for her contribution in new material and her close, expert review of the chapters I’d already written, this book might have been another year in the making.  The Guide was always my baby, but I couldn’t be happier that I decided to share it with Estelle, nor prouder that her name will be on the cover with mine.

Speaking of major changes, I probably wouldn’t have learned AsciiDoc, nor adopted Atom as an authoring environment (I still use BBEdit for heavy-lift text processing, as well as most of my coding).  O’Reilly used to be a “give us your Word docs!” shop like everyone else, but that toolchain doesn’t really exist any more, from what I can tell.  In fact, the first few chapters I’d given them were in Word.  When I finally returned to writing, they had to give me those chapters back as AsciiDoc exports, so I could make updates and push them to O’Reilly’s internal repository.  The files I created to create figures in the book went into their own public repository, which I’ll get to reorganizing once the text is all settled and the figure numbers are locked in.  (Primary to do: create chapter lists of figures, linked to the specific files that were used to create those figures.  Secondary to do: clean up the cruft.)

As of this moment, the table of contents is:

  • Preface
  1. CSS and Documents
  2. Selectors
  3. Specificity and the Cascade
  4. Values, Units, and Colors
  5. Fonts
  6. Text Properties
  7. Basic Visual Formatting
  8. Padding, Borders, Outlines, and Margins
  9. Colors, Backgrounds, and Gradients
  10. Floating and Shapes
  11. Positioning
  12. Flexible Box Layout
  13. Grid Layout
  14. Table Layout in CSS
  15. Lists and Generated Content
  16. Transforms
  17. Transitions
  18. Animation
  19. Filters, Blending, Clipping, and Masking
  20. Media-Dependent Styling
  • Appendix A: Animatable Properties
  • Appendix B: Basic Property Reference
  • Appendix C: Color Equivalence Table

Disclaimer: the ordering and titles could potentially change, though I have no expectation of either.

I don’t have a specific timeline for release as yet, but as soon as I get one, I’ll let everyone know in a post here, as well as the usual channels.  I expect it to be relatively speedy, like the next couple of months.  Once production does their thing, we’ll get it through the QC process — checking to make sure the figures are in the right places and sizes, making sure no syntax formatting got borked, that kind of thing — and then it’ll be a matter of getting it out the door.

And just in case anyone saw there was news about O’Reilly’s change in distribution and is wondering what that means: you can still buy the paper book or the e-book from your favorite retailer, whether that’s Amazon or someone else.  You just won’t be able to buy direct from O’Reilly any more, except in the sense that subscribing to their Safari service gives you access to the e-book.  That does mean a tiny bit less in royalties for me and Estelle, since direct paper sales were always the highest earners.  Then again, hardly anyone ever bought their paper copies direct from O’Reilly, so honestly, the difference will be negligible.  I might’ve been able to buy an extra cup of coffee or two, if I drank coffee.

It feels…well, honestly, it feels weird to have finally reached this point, after such a long time.  I wish I’d gotten here sooner for a whole host of reasons, but this is where we are, and regardless of anything else, I’m proud of what Estelle and I have created.  I’m really looking forward to getting into your hands.


Gridded Headings v. Justified Headings

Published 7 years, 6 months past

Amongst the reactions to Gridded Headings, Benjamin de Cock pointed out there’s another way to arrive at the same place I did.  Instead of this:

grid-template-columns:
    minmax(1em,1fr)
    minmax(min-content,max-content)
    minmax(1em,1fr);

…Benjamin pointed out one could instead do this:

justify-content: center;

That’s right: without explicitly specifying any grid columns, but just setting the grid items themselves to be centered, the same behaviors emerge.  Clever!

What’s interesting is that the behaviors are not precisely the same.  While mostly identical behaviors occur with either approach, there are a few subtle differences and a much different possibility space.  I’ll consider each in turn.

First, the differences.  First of all, the small gutters defined by the first and third grid column tracks — the ones defined to be minmax(1em,1fr) — aren’t present in the justify-content version.  This means the headings will jam right up against the edge of the grid container if things get narrow enough.

Side separation versus side smashing.  Grid on the left, justify-content on the right.

So we either need to re-establish them with grid-template-columns, which would seem to put us right back where we were, or else apply side margins to the heading and subheading.  Something like this:

div h2, div h3 {margin-right: 1rem; margin-left: 1rem;}

Either way, that side separation has to be defined (assuming you want it there).  Having to set those separations as margins feels a little clumsy to me, though not hugely so.  Doing all the sizing and separation in a single grid-template-columns declaration feels cleaner to me, though I admit that may be partly due to my current Gridfatuation.

There is another difference worth exploring.  If the content gets wider than the space available, the grid-template-columns approach means the content will overflow to the right (in LTR writing modes).  If it falls offscreen, it can be scrolled to read.  With justify-content: center, the content stays centered within the box, overflowing to both sides.  The content to the left may not be accessible via scrollbar.

How track sizing and content justification handle overspill.  Grid on the left, justify-content on the right.

So if you have a large headline containing a lengthy unhyphenated word, like “Kazakhstan” or “emoluments”, you might prefer one result over the other.

Beyond that, the further possibilities are a lot richer with Grid than with content justification.  Center-justifying the content means exactly that: the element boxes are centered.  So if you were interested in taking the heading and subheading, acting as an apparent unit, and shift them toward one side or another, this would be much easier to accomplish with Grid.

Suppose we want there to be three times as much space to one side of the headings’ column as the other.  Here’s what that would look like:

grid-template-columns:
    minmax(1em,1fr)
    minmax(min-content,max-content)
    minmax(1em,3fr);

That’s it.  One number changed, and the whole setup is offset from the center without losing the coherence of the original demo.

The same thing could likely be approximated with justify-content using side margins on the heading elements, but it wouldn’t be precisely the same, even with percentages.  fr is a very special beast, and permits very unique results.

The other major difference in possibilities is that with Grid, we can rearrange elements visually without ever touching the source.  Suppose we wanted to put the subhead above the heading in some layouts, but not others.  (Whether those different designs live on different pages or at different breakpoints, it really doesn’t matter.)  With Grid, that’s as simple as rewriting the grid template in a line or three of CSS.  The h2 remains ahead of h3 in the HTML.

With justify-content, you’d still have to write that same grid template, or else switch to flexbox and use flex-direction: column-reverse or some such.  That would work if you want to just switch the display order of two headings in a single column.  It tends to fall down for anything more demanding than that.

This is not to say Benjamin came up with a bad alternative!  I like it quite a bit, precisely because it has similar outcomes to my original idea, thus shedding light on creative ways Grid and content alignment can be combined.  But I like it even more for its differences, which shed even more light on how the two things operate.

In that combination of similarity and difference, I can sense an incredible range of capability, chock full of nuance and brimming with possibility.  There are going to be ways to put these things together that nobody has figured out yet.  I know I keep saying this, but there’s a vast landscape opening, so vast that I don’t think we can even guess how far it extends yet, let alone have mapped its terrain.


Gridded Headings

Published 7 years, 6 months past

In my ongoing experiments with both a realignment of meyerweb’s design and CSS Grid, I came up with an interesting heading-and-subheading technique I’d like to share.  It allows two elements to be centered as a block, while letting them text-align with respect to each other, while still line-wrapping if necessary.

Here’s a little demobox.

These Are Grid Headings

A useful technique

Boxes and Alignment

It’s the new hotness

Cool

This is pretty darned easy to implement

Gridded Headings

Wednesday, 19 May 2017

Each heading-subheading pair is composed of two heading elements wrapped in another element.  The wrapping element is the grid container for the headings, each of which become grid items.  This is the markup I used:

<div>
    <h2>These Are Grid Headings</h2>
    <h3>A useful technique</h3>
</div>

If you resize your browser window, or select the “Narrow” option, you should see that the boxes surrounding the headings stays as wide as the wider of the two headings.  It “shrink-wraps” them, visually speaking.  In addition, those boxes stay centered within the grid container.

Furthermore, given the demo’s defaults, the two headings are left-aligned with respect to each other.  You can change this: for example, if you choose to “Center-align headings”, the h2s will center when they’re shorter than the subheadings (the h3s).  On the other hand, if you select “Right-align subheads”, then the subheads will right-align themselves with respect to the headings whenever the subhead is shorter in length.

That was actually a bit misleading: if the headings are centered, they’re centered whether or not they’re shorter than the subhead.  It’s just that, if they’re longer, you can’t see that they’re centered, because left-, center-, and right-aligning them has the same effect.  Ditto for right-aligning the subheads: if they’re longer, they sit in the same place regardless of their text alignment.

The alignments hold even when line-wrapping kicks in.  Try narrowing things down to the point that the text starts wrapping.  If you’re having trouble visualizing the two elements, turn on “Separate backgrounds” to given the heads and subheads visually distinct background colors.

So: a centered box as wide as the longest of the two elements, inside which they can align themselves with respect to each other.  Here’s the CSS that makes this possible:

display: grid;
grid-template-columns:
    minmax(1em,1fr)
    minmax(min-content,max-content)
    minmax(1em,1fr);

That’s pretty much it.  The first and third grid tracks are set to be a minimum of 1em, and a maximum of 1fr.  Given the second track (which I’ll get to in a moment), this means the two tracks will split any free space within the grid container, down to a minimum of 1em.  That’s how the centering of the box work; or, if you turn off “Boxes”, how the unbounded text sticks together in the center of the layout area.

That second track, minmax(min-content,max-content), is what makes all the unusual aspects of this possible.  What that says is: “make this grid track no narrower than the narrowest of the grid items in the track, and no wider than the widest grid item”.  In practice, it’ll most likely be as wide as its widest element.

But if I just said max-content (without having the minmax() and min-content parts) for that track width, the track would always be as wide as the widest element at its widest possible layout, which in this case means without line-wrapping the contents.  That would force particularly long headings to run outside of the track, and possibly out of the grid container altogether.  You can see this by enabling “Remove minmax” and narrowing things until text lines should wrap.

It’s the minmax(min-content,max-content) that avoids this fate, because that means that while the grid track (the column the head and subhead share) can’t get any wider than the widest element it contains, it’s allowed to get narrower.  Thus, if the grid container gets too narrow to fit all the grid items’ maximum widths, the contents of the grid items are able to line-wrap, thus avoiding overspill.  In fact, the grid items can keep getting more narrow until they reach min-content, which is to say, the narrowest the track can get without having content of any grid item stick out of the track.  Then it will stop shrinking.

And finally, if you want to see how the options you’ve selected will look in a Gridless browser, select “Remove grids” and see what happens.  Some combinations may not be palatable without Grid, but remember: you can always use @supports(display: grid) to quarantine any styles that are particularly egregious in older UAs.

So there you have it.  While I’m not certain the Grid drop quotes I wrote about last month will be used in the final version of my styles — I’m still looking to see if they’ll fit with more than 17 years of vaguely ad-hoc markup patterns — it’s pretty close to certain I will use these headings, minus the boxes.  I think they’re a neat effect for blog post titles and dates.

Addendum: As of May 2017, WebKit browsers (e.g. Safari) require vendor prefixes for the min-content and max-content keywords.


Grid Drop Quotes, Revisited

Published 7 years, 7 months past

In last week’s Grid-Powered Drop Quotes, I overlooked a potential problem with the styles I created.  Fortunately, Philippe Wittenbergh caught it and pointed it out, and we both hit on the same solution.

The problem-in-waiting is that the big drop quote will force a gap between the first child element of the blockquote and the second, if the first child is short.  You can see this in the demo below (external version also available), where I made the first paragraph only a few words long.  If you select the “Borders” option, you can see the problem more clearly.

Besides, Grid was coming.

In the run-up to Grid support being released to the public, I was focused on learning and teaching Grid, creating test cases, and using it to build figures for publication.  And then, March 7th, 2017, it shipped to the public in Firefox 52.  I tweeted and posted an article and demo I’d put together the night before, and sat back in wonderment that the day had finally come to pass.  After 20+ years of CSS, finally, a real layout system, a set of properties and values designed from the outset for that purpose.

And then I decided, more or less in that moment, to convert my personal site to use Grid for its main-level layout.  It took me less than five minutes…

The solution is to have the drop quote span multiple rows.  The original CSS went something like this, simplified for the sake of clarity:

blockquote::before {
    grid-column: 1;
    content: "“";
    font-size: 5em;
}

That suffices to drop the drop quote into column 1 (explicitly) and row one (implicitly).  The row is as tall as the tallest of the grid items it contains, so in this case, the quote controls the row height.

The fix:

blockquote::before {
    grid-row: 1 / span 10;
    grid-column: 1;
    content: "“";
    font-size: 5em;
}

You can see that effect by enabling the “Row span” option.  I recommend trying it first with borders turned on, just to see how the element boxes change.

But wait!  Why span 10?  There aren’t that many rows in the blockquote, because there aren’t that many child elements!  That’s okay: the extra rows will be auto-created, but because they contain no content, the rows are of no height.  This means that in cases where there’s a blockquote with a lot of short child elements — think a passage of snappy dialogue — the pseudo-element will have more than enough spannability.  I could’ve gone with span 5 or similar, to echo the font sizing of the drop quote, but no sense risking having too little spannability.  (Which is a word I made up, then discovered it seems to have a meaning in mathematics, so I hope I’m not implying some sort of topological set unity of something.)

Auto-row generation may seem like dark magic, but you’re already soaking in it: remember how none of the blockquote’s child elements are explicitly given a row number, nor did I define rows with the grid-template-rows property?  That means they’re all auto-created rows.  This means if you do something like specify grid-auto-rows: 1em, then all the rows will be one em tall, with the contents spilling out and overlapping with each other.  For extra fun, try setting your auto row height to 0px instead!  (Warning: do not attempt where prohibited by law.)

The other thing Philippe pointed out was that in cases where the blockquote has only a single child element that’s one or two lines tall, the drop quote will not only set the height of the row, but the entire grid.  You can create this situation by selecting the “Short quote” option; again, I recommend leaving “Borders” enabled so you can see what’s happening.

Philippe’s proposal was to bring the line-height of the drop quote to nothing or almost nothing, and add some top margin to make up the difference.  For example:

blockquote::before {
    grid-column: 1;
    content: "“";
    font-size: 5em;
    line-height: 1px;
    margin-top: 0.33em;
}

This certainly works, as you can see by selecting the “Line height” option.  My concern is that having a great big drop quote next to a single-line blockquote is…not optimal.  I’d be more inclined to add a class for short blockquotes, and then restrict the drop quote effect to blockquotes without that class.  For example:

blockquote:not(.short)::before {
    grid-column: 1;
    content: "“";
    font-size: 5em;
}

That removes the need to fiddle with line heights and top margins, in exchange for remembering to class appropriately.  That’s a fair trade as far as I’m concerned.  Your preference may vary, of course.

Many thanks to Philippe for pointing out the error and proposing solutions!


Grid-Powered Drop Quotes

Published 7 years, 7 months past

I’ve been experimenting with CSS Grid for various layout treatments — not high-level, whole-page layouts, but focused bits of design.  I’d like to share one of them for a few reasons.  Partly it’s because I like what I came up with.  More importantly, though, I think it illustrates a few principles and uses of CSS Grid that might not be immediately intuitively obvious.

First, here’s an interactive demo of the thing I’m going to be talking about.  You can use the checkboxes to alter aspects of the example, whether singly or in combination.  Feel free to fiddle with them before reading the rest of the article, or but you’ll probably want to come back to the demonstration as you read.  There’s also an external version of the demo as a standalone file, if you prefer opening it in a new tab and flipping back and forth.

So that’s how things have been laid out since the middle of 2005, more or less. I fiddled with a flexbox layout at one point as an experiment, but never shipped it, because it felt clumsy to be using a one-dimensional layout tool to manage a two-dimensional layout. I probably should have converted the navigation bar to flexbox, but I got distracted by something else and never returned to the effort.

Besides, Grid was coming. In the run-up to Grid support being released to the public, I was focused on learning and teaching Grid, creating test cases, and using it to build figures for publication.  And then, March 7th, 2017, it shipped to the public in Firefox 52.  I tweeted and posted an article and demo I’d put together the night before, and sat back in wonderment that the day had finally come to pass.  After 20+ years of CSS, finally, a real layout system, a set of properties and values designed from the outset for that purpose.

And then I decided, more or less in that moment, to convert my personal site to use Grid for its main-level layout.  It took me less than five minutes…

Let’s dig in!  The core concept here is a Grid-powered version of the big drop-quote on the left side, there, which is a relatively common treatment for blockquotes.  To make this happen, I’ve applied display: grid to the blockquote element itself, and added the opening quote using generated content, like so:

blockquote {
   display: grid;
   grid-template-columns: -webkit-min-content 1fr;
   grid-template-columns: min-content 1fr;
}
blockquote::before {
   grid-column: 1;
   content: "“";
   font-size: 5em;
   font-weight: bold;
}

There’s more to the actual styles of both rules, but that’s the central thesis: set up a two-column grid, and generate a great big opening quote.

The first thing to note here is that generated content also generates a pseudo-element that can be styled.  You may already realize this, since it’s known we can style generated content separately from the main content of the element.  But given that, if a grid is applied to the element, then any generated content’s pseudo-element, whether ::before or ::after, will become a grid item.  You can then place it in the grid.

I first came across this concept in the comments on my ALA article “Practical CSS Grid”, where Šime proposed using generated elements as a hack to get around the inability to directly style grid cells.  Here, I’m just using one to push a quote over to the side.

Why do this, when we can already use floats or relative/absolute positioning approaches to do the same?  Because it’s not quite the same: with Grid, the column containing the drop-quote responds to any changes to the quotation symbol.  Change the font, change its size, have the preferred font fail and fall back to an unexpected face, or replace the character with an SVG image, and the first column will resize thanks to the min-content track sizing, and the actual main content of the blockquote will adjust its placement to accommodate.  That didn’t happen with earlier techniques.

And yes, there is a vendor prefix in there.  Safari’s 10.1 Grid support came with -webkit- prefixed versions of min-content, max-content, and fit-content.  So I did the old pattern of prefixed first, unprefixed second.  This should be necessary only until the next release; Safari has already dropped the prefixes in its latest Technology Preview builds.  The change apparently just didn’t quite make the cut for 10.1.  It’s sad, but it’s also temporary.

In the meantime, this does mean that if you want to restrict your Grid styles only to implementations that don’t require prefixes, use that in your feature queries:

@supports (grid-template-columns: min-content) {…}

That, as well as a number of close variants like using grid-template-rows or max-content, will keep your Grid styles away from Safari until they update their Grid support in the public release channel.

That’s all nice, but there’s a great deal more to learn!  If you use the “Border” checkbox in the demo, you’ll see a dotted red border around the drop quote’s pseudo-element.  Notice that it matches the height of the opening paragraph, not the entire height of the blockquote.  That’s because the pseudo-element and the first paragraph share a row track.  The following paragraphs are in their own row tracks.

This brings up two things to consider.  First, all the child elements of the blockquote are now grid items.  That means the drop quote’s pseudo-element, but also all the paragraphs contained by the blockquote.  The same would happen to any child elements.  We could get around that by wrapping all the contents of the blockquote in a div or something like that, but I’d rather not.  So, this grid has four grid items: the pseudo-element, and three paragraphs.

This leads us to the second consideration: without placing the paragraphs into the same column, they’ll auto-flow into whatever grid cells are available.  You can see this by selecting the “Auto placement” option.  The first column will contain the quote and the second paragraph, as narrow as they both can be due to min-content.  The second column will contain the first and third paragraphs.

How I get around this in the working version is to explicitly put all the paragraphs — really, all child elements of the blockquote, which just happen in the case to be paragraphs — into the second column, like this:

blockquote > * {grid-column: 2;}

Okay, but how do they end up stacked vertically?  After all, I didn’t assign each of those child elements to a row, did I?

Wait a minute.  What rows?

If you go back and look at the CSS I showed, there is nothing about rows.  The property grid-template-rows exists, but I didn’t use it.  All I did was define columns.

Each child element goes into a row of its own anyway, because Grid has the ability to automatically create columns or rows when needed.  Suppose you define a three-by-three grid, and then assign a grid item to the fifth column of the fourth row.  What should happen?  The browser should auto-create as many columns and rows as needed.  Any auto-created tracks will have zero width or height if they don’t contain any grid items, unless you size them using grid-auto-columns or grid-auto-rows, but we’re not going there today.  The point is, here I’ve said all of the blockquote’s child elements should go into column 2.  Given that, they’ll auto-fill rows as available and auto-create rows as needed, filling them in once they’re created.

So the blockquote in the demo above has two columns because I explicitly defined them, and three rows because that’s what it needed to create to handle the three child elements.  If I’d added two more paragraphs and an unordered list, the grid would have had two columns and six rows (because six chid elements).

There are a lot of possible extensions to this technique.  A close quote could be created using ::after and placed in the last row of the grid, thanks to the ability to use negative track values to count back from the end of the grid.  Thus:

blockquote::after {
   grid-column: 3;
   grid-row: -1;
   content: "”";
   font-size: 5em;
   font-weight: bold;   
}

That places the close-quote in the third column, so to the right of the quoted text, and in the last row, regardless of how many rows were auto-created.  Of course, there is no third column…or there wasn’t, until assigning something to the third column.  At the point, the browser created it.

The danger there is that the auto-generated column is essentially tacked on to the trailing edge of the grid, without real consideration for what might be in the way — up to and including the edge of the viewport. Rather than auto-generate the column, we could define a third column like so:

grid-template-columns: min-content 1fr min-content;

This sets up a column on each side of the grid, one for each of the big quotes.  The second column, the one that gets all the actual child elements of the blockquote, receives all the space left over after those outer columns are sized, thanks to its 1fr value.

There’s one more drawback here, albeit one that’s easily overcome.  Grid items’ margins do not collapse.  You can see this effect by checking the “Default margins” option in the demo.  That shows what happens if default paragraph margins are allowed to remain.  We end up with two ems of space between the paragraphs, because each has top and bottom margins of 1em.

In the normal flow, margins collapse to the largest of the adjacent margins, which is why we’re used to 1em of space between adjacent paragraphs.  With grid items, what we see instead is the full element box, margins and all, placed inside the grid cell(s) they occupy.  That means any margin will create space between the edge of the grid cell and the border-edge of the element.  The fix here is straightforward: add a style to reduce margins between elements.  For example, something like:

blockquote > * {
   grid-column: 2;
   margin: 0.5em 0;
}

With a half-em margin above and below each element, any two adjacent elements will have the common 1em separation.  The demo actually has less than that because I wanted to use the print convention of paragraphs with the first lines indented, and a minor separation between paragraphs.  So the actual demo styles are more like this:

blockquote > * {
   grid-column: 2;
   margin: 0.125em 0;
   text-indent: 2.5em;
}
blockquote > *:first-child {
   text-indent: 0;
}

So there you have it: a Grid-powered drop quote.  I should note that all this by itself isn’t quite sufficient: if Grid isn’t supported, it will degrade poorly, as you can verify with the “Disable grid” option.

This is where using @supports() to encapsulate the Grid styling comes in handy.  You can put all of the quote-generation styles into the @supports() block, so that downlevel browsers just don’t get the drop quotes; or, you can set up the drop quotes with floats or positioning and then override those with @supports()-protected Grid styles.  Either one works.

Fortunately, we do have that capability, so it’s fairly easy to progressively enhance your designs with little touches like this one, even if you’re not ready for a full-on Grid plunge.  I’m looking forward to deploying this pattern here on meyerweb, as part of a site design overhaul I’ve been working on for the past couple of weeks.  That’s right: I’m working on my first redesign in a dozen years.  If that doesn’t give you some sense of the power of Grid, well, I just don’t know what will.


There is a followup to this article that explains and corrects an oversight in this article.


Browse the Archive

Earlier Entries

Later Entries