Killer Responsive Layouts With CSS Regions

Advertisement

As Web designers, we are largely constrained by the layout features available to us. Content placed inside a container will often naturally extend the container vertically, wrapping the content. If a design requires elements to remain a certain height, then our options are limited. In these cases, we can only add a scroll bar or hide the overflow. The CSS Regions specification provides a new option.

Support

Regions are a new part of the CSS specification, so not all browsers have implemented them, and in some cases you might have to enable a flag to use them. They have recently gained support in iOS7 and Safari 7, as well as Safari 6.1+. Adobe maintains a list of supported browsers and instructions on enabling regions and other features. However, support for regions is constantly growing. For a robust list of which browsers have implemented regions and the various features available, see Adobe’s “CSS Regions Support” page.

Regions 101

CSS regions enable us to disperse content across multiple containing elements. They provide a flow, which consists of content that may appear within multiple elements, and a region chain, which is the collection of elements the flow is spread across. Once these elements have been defined, the flow dynamically fills the elements in the region chain. We can then size our containers vertically without worrying about the content getting cut off, because it simply overflows into next element in the chain. This creates new opportunities for layout with responsive design.

To use regions, start by creating a named flow; simply add the CSS property flow-into to your content element, with the value of your flow’s name. Then, for each region through which you want the content to flow, apply the CSS property flow-from with the same flow name value. The content element will then flow through the region elements. Current implementations in browsers require the property to be prefixed, but we are using the unprefixed version here.

#myContent {
	flow-into: myNamedFlow;
}

.myRegion {
	flow-from: myNamedFlow;
}

Your HTML would contain a content element and the scaffolding of all of the regions that this content will flow through. When you use regions, the content element will not be visible in its original location and any HTML already in your region elements will disappear, replaced by the content being flowed into them. Because of this, we can have placeholder or fallback content within our region elements.

<div class="myRegion"></div>
<div class="myRegion"></div>
<div class="myRegion"></div>

<div id="myContent">...</div>

When using regions, the content being flowed is not a child of the region elements. You are only changing where the content is displayed. According to the DOM, everything remains the same, so the content does not inherit styles from the region in which it lives. Instead, the specification defines a CSS pseudo-selector, ::region(), which allows you to style the content within a region. Apply the pseudo-element to the region’s selector and then pass a selector as an argument, specifying the elements that will be styled within a particular region.

.myRegion::region(p){
    /*styles for all the paragraphs flowing inside our regions*/
}

Responsive Design With Regions

Responsive design is the technique of creating malleable layouts that stretch and change according to the given context. Frequently, designers will make elements flexible with percentages and media queries to adapt a layout to different screen sizes. Responsive design adapts content to every screen without requiring the designer to completely overhaul the design or code.

Regions facilitate responsive design in several ways. First, you no longer have to rely on height: auto for every element to ensure content fits. Instead, you can allow the content to flow into different elements within the layout. This means that the content does not dictate the layout, but rather adapts to the intended design. You can still use height: auto on the last region in the chain to ensure that it extends to display all remaining content. You can see this technique in the CodePen example below.

See the Pen Region Auto Height by CJ Gammon (@cjgammon) on CodePen.

Regions And Events

You can use JavaScript events with regions to manage your layout and to ensure that content is displayed properly. The regions specification defines events that you can use to respond to certain conditions. The regionoversetchange event is dispatched when the regionOverset property changes for any region. This can occur when a user resizes the page, stretching out the container element so that the content no longer flows into certain regions. The value of regionOverset is either fit, overset or empty. A value of empty specifies no content inside the region. The regionOverset property is set to overset when the last region in the chain is unable to display all of the remaining content, making some of the content unreadable.

The fit value sets content to fit within the region properly, either completely (if earlier in the chain) or partially (if it is the last region in the chain). How you respond to these events will depend on the design, content and other aspects of your layout. These events could be used to dynamically add or remove regions or to apply a class that changes the layout. You can see an example of the former technique in the CodePen below.

Note: Some implementations call the event regionlayoutupdate, instead of regionoversetchange, based on an earlier version of the specification.

See the Pen okmGu by CJ Gammon (@cjgammon) on CodePen.

Regions And Media Queries

Regions are defined entirely in CSS, making them easy to use in combination with media queries. In addition to resizing and positioning elements, you can completely change which elements are defined as regions. You can also set a region to display: none, which will cause it to be skipped entirely in the region chain. This capability makes it easy to remove particular regions from a layout without worrying about the continuity of the content. You can also use this technique to display whole new templates with completely different layouts, without ever changing the content.

Regions And Break Properties

Regions also extend break properties from the multi-column layout specification, which you can use to define how content breaks within your regions. You can apply these properties to elements within the flow either to always break or to avoid breaking a region relative to the element. Using the value region for break-before or break-after will always force a region to break before or after the element, respectively. The value avoid-region can be used for break-before, break-after or break-inside to prevent regions from breaking before, after or inside the element.

This technique is useful for keeping related elements grouped together and for preventing important elements from being split. The demo below shows images along the right column and long descriptive text flowing along the left. If you reduce the width of your browser, then media queries will change the layout, causing the images to redistribute over the narrower single-column structure. Applying break-after: region to the image containers ensures that a new region break will occur after each image in the image flow.

Note: Some implementations use non-standard regions-specific break properties with a region prefix; for example, region-break-before or, with a vendor prefix, -webkit-region-break-before.

Responsive Layout
The break-after property is applied to regions with media queries.

Regions And Viewport Units

Viewport units enable you to use the window (or viewport) as the basis for sizing elements, which creates a consistent aspect ratio and harmony in the layout. You can simulate pages or blocks that break up the content cohesively. A potential pitfall of this approach is that, if you use the aspect ratio of the device to size containers, defining both the width and the height, then your content might no longer fit inside the containers.

You could, however, use regions to break up the content while respecting the variable-sized elements across different screen sizes. You can see this technique being applied in the “Demo for National Geographic Orphan Elephants.” On this website, images and text are alternated to maintain the height of the viewport. We use regions to flow the content through all of the text sections, and we adjust them when the user shrinks the screen.

elephant-demo2
Regions being used with viewport units. Notice how the image fits the window exactly. (Large view)

The typical navigation paradigm for magazines and books on a tablet is pagination — i.e. enabling the user to swipe or tap to page through the content. As a designer, you want these pages to respond to a variety of screen sizes. Regions are particularly useful for this kind of layout, because you can size columns using viewport units and create a variety of different layouts that enable content to flow across the columns. An example of this done in HTML is shown in the video below:

The Kindle Cloud Reader website has a similar two-page spread but uses JavaScript to manage the layout. Implementing this kind of layout in JavaScript requires significant development overhead, and manipulating the DOM so heavily will usually incur a performance penalty. You can use regions to bring these capabilities natively to the browser, increasing the website’s performance while reducing development time.

Debugging

When working with regions, it’s helpful to have tools to easily manage and debug various features. In Chrome Developer Tools, you can enable debugging features specific to regions. Detailed instructions on enabling these tools can be found in Christian Cantrell’s post “Web Inspector Support for CSS Regions.” With these features, you can find all of the named flows in a document, find the content and region chain associated with each named flow, and get visual cues for whether content fits in a region based on the regionOverset property.

Webkit Nightly also has some helpful visual cues. When you open the Web Inspector and inspect a region’s container, you will see a region number and links between the region containers showing the flow of the content.

region_debugging
Webkit Nightly allows you to inspect region containers, showing their number and the flow chain.

Further Reading

Regions open up many new opportunities for designing responsively and ensuring that content looks great at any size. One responsive website whose unique layout was created with regions is Adobe’s demo for a bike company, created with Edge Reflow. Follow @adobeweb for the latest updates on regions and other new Web features. Also, be sure to check out Adobe’s CodePen collection, which shows regions in use; you may want to fork one or more of the examples to explore different ways to use regions.

For more on regions, visit Adobe’s Web Platform Team Blog, which often provides updates about the specification and implementations. Full details can be found in the CSS Regions specification, which outlines all of the topics covered here and more. You can also find more information and examples in the “Regions” section of Adobe & HTML.

(al, il)

Front page image credits: Adobe & HTML

↑ Back to top

CJ Gammon is a Creative Technologist at Adobe focusing on new web technology. With the goal to showcase the creative potential of the web and inspire the community through innovative applications and experiences.

  1. 1

    I see prefixed proprieties on the tests… people from the future browsers will cannot use they.
    PS: why people still keep prefixing code? That’s a bad habit: we have lots and lots of auto-prefixers today.

    0
    • 2

      If flagged, then prefixed (and these new css features are flagged – you have to switch it on e.g. in Chrome).
      And nowadays browsers do exactyl as you stated. If testing is stable, browser vendors activate a feature without prefix.

      0
      • 3

        well they all should use the same prefix then. “demo-” or “beta-”
        It’s simply ridiculous to have a CSS rule 5 to 6 times with all prefixes.

        0
        • 4

          Not all browsers have implemented an experimental feature in exactly the same syntax. Look at the early days of most CSS3 rules. By using the browser pre-fix, you target that browser with it’s proper syntax. Remember, most of the specs are drafts, not finished standards, so there is bound to be slight differences in implementation.

          0
          • 5

            Targeting browsers is a practice left behind in IE6 days. In theory, the prefixes help browsers implement new features, but in practice, if a feature appears differently in every browser, the developer will not use that method. For example, if only Firefox supported text-shadowing, I’m not going to have the “well it only works in this browser, this version, if this is in place and…” conversation with my design team. That causes mayhem. “Can’t you code a workaround?” Not in this case. “Can we just use an image?” Absolutely not. “Okay I’ll have to revise my design.” Now, as soon as the text-shadow is removed in the design, not much changes, most wouldn’t notice but it completely breaks the vision the designer had and suddenly, no amount of tweaking will ever make it perfect again. She’ll toss the thing and re-think the entire thing. That’s how design works – it’s perfect. Being that for a decade, people actually used this cycle to create websites and learned hard lessons. How do you take a team of designers who are trained to perfect visual experience and get a realistically possible design? Easy. First, break the pixel habit. “This needs to be 18px with 5px margin.” Don’t pixel push me. Give me a scale. “Just a tad larger than the body copy.” Bingo. Now you’re ready to ease them into acceptance that every browser will break their design in a different, unpredictable way that is perfectly normal and undetectable to those who will be using it. Just effing remove the text-shadow if it only works on Firefox. Finish the stupid document already – quick – hurry before the designer walks in and notices it before she can see the whole thing built. “Looks good, but didn’t I have a shadow on that text?” Doesn’t work. “Can’t we just slice a PNG?” NO! “Okay, let’s show the boss.”

            There. I just saved a week of work for you. Tweaking a designer’s work around “targets” is like taking sandpaper to their heart. It’s like their baby. They will never run out of hope that it can be made to work. You’ll smash hour a week in Notepad, read 10000 articles, poke and prod and finally come up with the 120-line code monster to do something as insignificant as shadow text. Be innovative in code, don’t code innovation. No one uses browser prefixes as they were planned. They have added huge payloads to CSS files and are a nightmare to manage. They are literally repeats of the same code over and over again with the sour excuse that “it’s not standardized yet.” PFFT. Ain’t nobody got time for that. W3 won’t accept a rolling CSS standard despite the reality being that in our post-IE world, we’re rolling CSS standards with or without them. Browsers have slight differences in the way things are rendered, even for features implemented in the ’90s. Tedious targeting of pretend-experimental (if it’s experimental, how do you explain that cross-browser support was there years ago and developers are already using the feature?)

            I’m just experimenting here.
            .simple-interaction-that-will-not-make-or-break-the-delivery-of-this-user-experience-if-it-doesnt-work {
            webkit-transform: rotate(45deg);
            -ms-transform: rotate(45deg); /* LOL yeah right */
            -moz-transform: rotate(45deg);
            -o-transform: rotate(45deg); /* designed to use the webkit prefix anyway since Opera blamed developers for the prefix nightmare, completely negating the false benefits provided by “targeting”, apparently deciding to allow a browser with 0.25% usage share and some nasty rendering quirks to gracefully degrade makes me a bad developer in Opera’s eyes. In my eyes, “Who’s Opera again?” Oh, the one that has 0.001% of our analytic hits? Why do we need thousands of extra lines of code to add prefixes for this? Screw that, the one user who uses Opera can just not have gradients and transforms so the thousands of users trying to pull down this CSS file on 3G don’t have to suffer. Yeah, developer’s fault, totally not a lesson for Opera here about their place on the food chain. (Hint: you’ve gone extinct. Sorry. I was rooting for you, though. Well, until you issued a statement blaming us for prefixing nightmares. Go install yourself on a Nintendo Wii and get outta my face!) */
            -tom-transform: rotate(45deg);
            -dick-transform: rotate(45deg);
            -harry-transform: rotate(45deg);
            transform: rotate(45deg);
            }

            Holy constants, Batman! It appears every browser agrees that 45-degrees is effing 45-degrees and there’s really nothing any more complicated than that! Does this mean we can stop prefixing these stupid things already!

            Sorry, Robin, W3 is still beating a dead horse over the “deg” part of the code. The problem raised two years ago was that the “deg” part is unnecessary and “45″ should just do the trick. They’ve been fighting over it ever since.

            Holy discord, Batman! So you’re saying someone is obstructing the standardization of this module over a code procedure already in standard use by devs, browsers and in millions of CSS files out on the web and is therefore breaking the existing web over the idea that “deg” will break the web of the future? You mean they don’t realize the web of the future is already being used and they are already breaking it by dragging their feet instead of tossing CSS on the rolling wheel of sensibility?

            Is the W3 the Congressional GOP now?

            0
  2. 6

    Cant wait to use this especially on Adobe DPS!

    0
  3. 7

    Cool, I’ll use it eventually. Until then, CSS and JS for fluid grids, media queries, DOM manipulation and breakpoints! I for one love responsive design!

    0
  4. 8

    Cool feature, but because of IE we cannot use it for general sites until (maybe?) 2020. Meanwhile, only for mobile, but then you design just for narrower pages and you also don’t need it so much.
    There is also the issue that web development is getting more and more complex. Maybe we just need another completely diferent way. We could do it, it would be implemented by now only for auto-updating browsers, but so what?

    0
  5. 11

    Gabriele Romanato

    November 6, 2013 10:39 am

    This feature makes browser development too much bloated. I think that adding layers after layers of complexity to the CSS specs is harmful in the sense that CSS was designed to be accessible both to authors and users. Many people often forget that in CSS a user stylesheet is the king. The problem now is that there are too many complicated things to learn which typically a casual user cannot understand properly. The balance between user’s needs and author’s needs has become unbalanced (no pun intended) if favor of authors ( web developers and site owners ). We’re spoiling the original design of CSS.

    0
    • 12

      On the contrary, it makes web development *easier*.
      To achieve similar layout control right now requires a great deal of code hacking.

      One of the issues we face with responsive, is positioning content and that’s why this is so important.
      There’s basic CSS techniques which use floats to *push* content above/below, implemented with media queries, but this method has limited scope.

      Then, as the article mentions, there’s javascript solutions too – but they are memory intensive and can get fairly complex.

      In closing, if your a typically casual user, why would additional CSS functionality bother you? There’s no impact in terms of any existing functionality – you can safely ignore anything you consider either too complicated, or un-important.

      0
  6. 13

    Regions and Viewports. What an excellent idea. I am certainly interested in giving that a go after seeing that demonstration video. Brilliant!

    0
  7. 14

    Why we are talking about all browser compatibility as people are using couple of browsers this days e.g. chrome, firefox, safari and explorer. Check this website http://www.clippingpathunique.com it’s compatible in all major browsers.

    0
  8. 15

    Great!

    0
  9. 16

    Twittstrap offers a Free flat version of Twitter Bootstrap Framework
    It’s not only that, Twittstrap also offers a large list of valuable Bootstrap resources that you can find at the following link http://twittstrap.com/resources

    0
  10. 17

    Are CSS regions harmful?

    At first, I didn’t think so. But this article (by Håkon Wium Lie), published @ A List Apart picked up my interest:

    http://alistapart.com/blog/post/css-regions-considered-harmful

    Worth reading it. :)

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top