Blog

Text-align: Justify and RWD

Tags: design, development, framework, front-end, grid, inline-block, justify, responsive, rwd.

March 12, 2013 by
blog_justify_cover

Did you know that one of the most powerful tools for fluid and responsive layout has been a native feature for every browser since HTML 4?

View/Edit Demo on CodePen

Background

While working on a project early last year, I quickly became frustrated having to re-calculate the margins between menu items in my full-width footer nav each time the client requested a new link in the menu.

Thinking about how “justified” text in Microsoft Word fills the entire width of the line by creating even word spacing, I wondered if the same principle could be applied to a menu of text links in HTML. Knowing that ‘text-align: justify’ was a long established CSS property (the descendent of HTML 4  attribute align=”justify”), I did some Googling for answers.

Sure enough, I found some discussions on StackOverflow about justified horizontal nav menus.

blog_justify_header
Fig. 1: An example of a full-width “justified” navigation menu.

How it works

In its natural state, ‘text-align: justify’ will not work unless the contents of the line are long enough to cause a line-break. Otherwise, the text remains left aligned. Incase you’re wondering why this is, it’s because in a typesetting situation this is the desired behavior - the final line of a block of justified text is always left aligned. Perhaps this was an oversight when the CSS spec was designed, but even if we only have one line of text, that one line still behaves like the final line.

It took me a few tries, but we can solve this problem by giving 100% width to an invisible inline element at the end of the line (shown in purple for demonstration purposes). As this “break” element is too wide to share a line with anything else but itself, it causes a line-break, thus becoming the final line, and  forces the words before it to justify (fig. 3).

Without a "break" element. As there are not enough elements to break the line, all elements will align left.
Fig. 2: Without a “break” element. As there are not enough elements to break the line, all elements will align left.
blog_justify_wbreak
Fig. 3: With a “break” element. The “break” element, shown as a purple dash, forces a line break due to its 100% width. All preceding inline elements are now justified.

Because ‘text-align: justify’ is designed to work on individual inline words, it works on any inline element—and more importantly any inline-block element.

As this particular project was a fixed grid, non-responsive site (remember when we used to build those?), the potential significance of this technique for RWD didn’t occur to me until later, when I started to combine it with percentage based inline-block elements.

Fig. 4 Justified "inline-block" elements. Note the "break" element is used to make sure the last row justifies.
Fig. 4 Justified “inline-block” elements. Note the “break” element is again used to force the last row of elements to justify.

Implications for Responsive Web Design

Almost all of our responsive designs at Barrel feature some sort of boxed content in a grid. Traditionally, the way I handled this was to give each element in the grid a percentage width, and then divide up the available leftover space into equal, percentage-based margins.

When I wanted my grid to go right to the edges, I would target the first and last element of each row using nth-of-type, and remove their left and right margins respectively. This already seemed like way too much calculation, and if a browser decides to round your percentages up instead of down when converting to pixels,  that one extra pixel is enough to cause elements to jump on to the next row at random (even though all widths and margins add up to 100%!).

I’m sure we’ve all grappled with some of these issues. Enter ‘text-align: justify’ to save the day!

You’ll never have to deal with horizontal margins ever again

By simply applying ‘text-align: justify’ to the container, and giving the child elements ‘display: inline-block’ and a percentage width, you’ll never have to deal with horizontal margins ever again! (Oh and did I mention, when using this trick, you’ll also never need to use float on your elements ever again, so you can wave goodbye to those ignominious  clearfixes and clear divs too!)

NB: We should be aware that when using ‘display: inline-block’, our elements will be at the mercy of various typographic CSS properties, including font-size, line-height, vertical-align and word-spacing. These properties will have a visible affect on your layout’s whitespace, but can be easily adjusted or removed as needed. In 99% of cases, setting ‘font-size: 0.1px;’ to the container and ‘vertical-align: top’ to the child elements should do the trick.

“Break” Elements

As mentioned earlier, the first caveat of this technique is that it is necessary to force each row to “break” before it will justify. If you have a multi-row grid, this won’t be necessary until you get to the last row, but it is crucial to the technique and there are two ways we can solve the problem.

1. Adding a “break” element as the last child in the container

<ul id="Grid">
	<li></li>
	<li></li>
	<li></li>
	<li></li>
	<li class="break"></li>
</ul>

With the following styling:

#Grid{
	text-align: justify;
	font-size: 0.1px; /*hide whitespace between elements*/
}

#Grid li{
	display: inline-block;
	width: 23%;
	...
}

#Grid .break{
	width: 100%;
	height: 0;
	...
}

2. Applying an ::after pseudo-element to the container

#Grid:after{
	content: '';
	display: inline-block;
	width: 100%;
}

I recommend the second method for cleaner, semantic markup.

“Placeholder” Elements

In this section I use the term “column” as a visual metaphor only, as we should all be aware that there is arguably no such thing as a vertical column, (or a grid for that matter) in HTML/CSS. One of the keys to understanding this technique is understanding that by default, HTML flows inline and horizontally across the page, left to right, line by line. By using text-align: justify, we are harnessing this characteristic instead of fighting against it with floats and absolute positioning.

The second caveat occurs in cases where we don’t have control over the number of elements in our grid.

Fig 5. Coming up short. As the last row of our grid is not complete, the justified margins are calculated based on two elements, and not four.
Fig 5. Coming up short. As the last row of our grid is not complete, the justified margins are calculated based on two elements, and not four.

Say you get to the last row of your four-column grid, and you only have two elements instead of the normal four—and you want those last two to align neatly with everything else—you will need to add invisible “placeholder” elements to make up the difference. This forces the browser to calculate the margins as if there were four items and not two (fig. 5).

If you had only one element on that last row, it wouldn’t be an issue—as it will always align left naturally. However, if you have any number of elements greater than one and less than the total columns per row, you will have to “fill in the gaps” manually with “placeholder” elements (fig. 6).

Fig. 6. "Placeholder" elements. This four-column grid requires two placeholders (shown in solid purple), to ensure margins are calculated correctly.
Fig. 6. “Placeholder” elements. This four-column grid requires two placeholders (shown in solid purple), to ensure margins are calculated correctly.

To account for any and all possible numbers of elements on the last row, the number of “placeholder” elements you will need to add is equal to the maximum number of elements per row, minus 2. These elements should be inserted at the end of your grid (before the “break” element if you are not using a pseudo-element to break the row) and then left alone. Since they do not occupy any vertical space, the “placeholder” elements won’t affect the layout if the last row is full or if your site is responsive and the number of elements per row changes. As long as you have enough placeholders for the widest view, you’ll be fine.

No. of placeholders = max elements per row – 2

Obviously, this has some semantic implications—as there is no way to create any of these placeholders using pseudo-elements. On a grid where the last row will always have the maximum number of elements, we don’t need to use placeholders at all (just a break), but in most CMS situations they are necessary, and should be hard-coded into your HTML.

Media Queries

Media queries can be used to dictate the number of columns in the grid based on viewport size. For each new column layout, we need only redefine our column width, and justify will take care of the rest. Check out the demo to see it in action across four different layouts (NB: Our demo also uses fluid, dynamic element height via the old padding-top trick).

Wider Uses

After having great success with this technique, I’ve started using it as a powerful layout tool for all sorts of applications. I rarely, if ever, need to use floats for layout anymore, and combined with media-queries, it becomes an incredibly powerful and time-efficient technique for tackling percentage-based fluid layouts.

It’s also just as useful on non fluid layouts, if you don’t want to spend time calculating your margins—why not let the browser do that work for you?

Why not let the browser do that work for you?

Perhaps most impressive, is the cross-browser compatibility of this technique. Because “justify” and “inline-block” have both been around for a very long time, this technique can be used confidently on IE7 and up (with a few small IE7 hacks!).

As a footnote, the main stimulus behind the creation of the MixItUp plugin was preserving the elegance of this technique on a grid that required dynamic client-side animated filtering. I knew that using masonry or isotope on it (both incredibly powerful plugins but perhaps overkill for a standard grid layout) would force absolute positioning on my elements, convert their percentage-based widths and heights into static pixels, and require a disproportionate amount of custom JavaScript to maintain the responsive behavior I had so easily achieved with CSS and media queries alone. So MixItUp was born, and I’m very excited with how the two techniques are working together so far.

If you’re interested in exploring this technique further, check out the following links:

Basic Examples:

Fully functioning grid demo
Further examples

Advanced Examples:

New Music USA (grants page, musician stories, blog)
Barrel NY (work page, team page, blog, and many other places!)
MixItUp (homepage and demos)

Enjoy!

  • Mike A

    That does the job. Amazing!
    I’ll definitely give it a try in my current project.

  • Mike A

    One thing I’ve noticed: this technique requires that there must be a margin between columns. For example, 3 columns, each 320px wide, won’t work in a 960px container. Make them 317px, and voila!

  • http://twitter.com/brandonewoldt brandon ewoldt

    This is great Patrick. I am planning on using this technique on a project of mine but before I do I wanted to ask how this technique is holding up since you first wrote this article and if you still recommend it?

    • barrelny

      Hi Brandon! Thanks for your interest – I’ve been using this method on various client sites and internal project for about 6 months now and I can confidently say it’s the fastest and most elegant method I know of to achieve a fluid, percentage-based grid. Our other Barrel devs have also been experimenting with it on various client projects and I’ve had very good feedback regarding how much less code they are having to write since adopting this method.

      There are a few quirks to be aware of if you are using inline-block for the first time, but I would say almost everything can be fixed with “font-size: 0.1px;” on your container, and “vertical-align: top;” on your child elements!

      You may also be interested in this new plugin we just launched which is closely related to this method: http://mixitup.io

      Good luck with your project and let me know if you have any other questions!

    • http://frazelledazzell.com/ Jessie Frazelle

      I just used this three different times on one site. Saved me so much time trying to keep items aligned with the grid. I honestly don’t know how I’ve lived without it for so long! :) Definitely recommend.

  • http://twitter.com/polmoneys Pol

    so simple it hurts. Thanks for sharing.

  • http://twitter.com/ActualGabe Gabriel Luethje

    This looks really cool to me especially for nav menus.

    But I notice that the 100% width :after element required to make the trick work creates a significant amount of vertical space (~20px) underneath, and I can’t seem to find a way around that. Am I missing something?

    In your demos you have the border there to visualize the “break” element that does the magic, but without the broder there’s empty space.

    I made a super simple reduced test case here: http://codepen.io/FStop/pen/Choma

    The space underneath the links is what I’m talking about. It goes away if the :after element on the ul goes away, but then so does the nifty justify trick. No styling tricks that I tried would get rid of that space.

    Any insight into that?

    • barrelny

      Hi Gabriel – good question! As noted in the article you have to watch out for various pesky typographic CSS properties dictating the size of whitespace in your layout. I’ve forked your codepen and set “font-size: 0.1px” on the container (we could do font-size: 0, but it breaks IE9).

      This little trick collapses white space in almost all cases. Always remember to override it on your child elements. If you check out my fork, you’ll see I reset it to font-size: 16px on the s.

      Hope that helps!

      http://codepen.io/patrickkunka/pen/wbaqp

      • http://twitter.com/ActualGabe Gabriel Luethje

        Ah, thanks. I can see that I should have read the article a bit more carefully for that bit.

        This is a really cool technique. Thanks for sharing!

        • Gcyrillus

          use line-height trick instead, it is safer and doesn’t disturb font-sizing : http://codepen.io/gcyrillus/pen/ruhCg

          • http://www.crocodillon.com/ Dillon de Voor

            My first tests were using line-height, but there is always Chrome who bugs out (the new IE I think :P ). Read my other comment about the bug :)

          • Gcyrillus

            :after { margin-top: -0.7em ; } should fix it. :)

    • Gcyrillus

      hello, you can erase this width a reset/unset of line-height (comments in CSS) test case revisited : http://codepen.io/gcyrillus/pen/ruhCg

  • http://highrockmedia.com/ High Rock Media

    You mention that in CMS situations, the placeholder should be hardcoded. I think this could be an issue though as I might have several different pages based on one template I’m creating so I can’t really hard code the placeholder as any given different page (based on that one template) might have a different number of elements each. I’m picturing the place holder could somehow be added with jQuery (count and then add the appropriate number of placeholders?) but I think it would be really complex compounded by the fact that my responsive layout has different numbers of columns depending on the media query. Any thoughts on this or am I missing something obvious? My early tests in a Drupal site I’m building (my photo site) are pretty good with the exception of that last row. Thanks.

    • barrelny

      We had an internal discussion about this a couple months ago when I presented the technique to my team and decided that hard-coding the placeholders (plural) is the best option, as the maximum number you will need will always be the same. For example on a 4 column grid, we will always need a maximum number of 2 placeholders, on a 6 column grid, we will need 4, etc, etc. It really doesn’t matter if you have more than you need, as they don’t occupy any vertical space in your layout (if styled correctly and whitespace is collapsed), and as such they will never be visible on the front-end.

      We realized that because of this, any attempt to count how many elements are in your grid (either on the client side with JS, or on the server side when parsing the template) would be a waste of time and code, as the max number of placeholders will serve you perfectly in every situation. You might end up with a couple more empty divs than you need, but it’s hardly going to break the browser’s back!

      I hope that makes sense!

      • http://highrockmedia.com/ High Rock Media

        ah, I see, that totally makes sense now. yay, I am close to getting this working. Thanks for all this, your body of work is very inspiring!

      • http://highrockmedia.com/ High Rock Media

        I just added an additional placeholder to my theme template, that’s all it took, it works like a charm. I’ve been going around with grids for the past several months but could not really figure out something that would work as well as this does. This method also works nicely with your mixitup plugin so it solves many problems. Thank you again!

        • barrelny

          Great to hear! Yes MixItUp was built with this method in mind.

  • Tab Atkins Jr.

    This is a pretty great hack. I’m happy to report that Flexbox retires this hack as well – just use “justify-content: space-between;” to get the same effect, and without the need for the break element.

    In Flexbox 2 I’ll solve the last-line problem better – for now, it has identical problems and solutions to what you’ve outlined in this article.

    • http://www.mathewporter.co.uk/ Matt Porter

      Was just about to say… I know this is a hack, but isnt flexbox the way to do this… Good job I saw Tab’s comment or I could have looked like a plum chatting away in this thread.

    • barrelny

      Hi Tab. I should probably add something regarding FlexBox – I haven’t worked with it much, due to the limited support in the past but I’m excited to start experimenting with it. I hope this method is still useful for people looking for greater backwards compatibility for their projects though. I’m not sure if I would even consider it a hack though – as fas I can see, it is essentially using inline-block and text-align, exactly as they are intended. The only hack would be concerning the break element.

      • Tab Atkins Jr.

        The reason it’s a hack is that you’re not using the inline-block elements as “text” – they’re blocks that happen to be laid out sideways rather than vertically. ‘text-align’ is meant for aligning text and text-like things, like sparklines. It’s just lucky that there’s a method for text that also works reasonably well for horizontal blocks.

        • barrelny

          By that logic would you consider inline-block itself to be a hack by nature? Seeing as text-align came first and inline-block was designed to react to text-alignment by having the characteristics of an inline object..

          • Tab Atkins Jr.

            No, inline-block has legit text-like uses. For example, buttons are inline-block.

  • Pingback: Using HTML4 concepts to justify navigation : Web Design With .Net

  • Pingback: Text-align: Justify and RWD | Bram.us

  • Kristofer Joseph

    This is really great. The only issue I see with this approach is having to redefine the font-size since setting a font-size of 0.1px breaks the cascade. A possibly only slightly better approach would be to use a relative unit to allow the base font size to continue to cascade.

    http://codepen.io/kristoferjoseph/pen/LtGcC

    • Gcyrillus

      I use line-height instead of font-size.See your codepen forked :http://codepen.io/gcyrillus/pen/ruhCg

      • http://www.crocodillon.com/ Dillon de Voor

        There is a bug in Chrome where if you only use a linebreak and no spaces after the last inline-block, it will leave a few px space visible after the last inline-block.

        You can even see it on your Pen right after Five. Adding a space before would fix it :)

        It’s documented on http://justifygrid.com/ under “Overcomming cross-browser difficulties”, that’s why I’m using font-size 0. Fool proof.

        • Gcyrillus

          pen is updated with the negative margin (it’s a trick used long ago to reduce height of used as hidden spacer :) )

      • djungle

        Using your codepen in chrome, the bottom 50% of the link is unclickable. FF, IE10 seem to be fine though.

    • barrelny

      As I said in the article, you can solve the white-space issues with line-height or word-spacing in addition to font-size. We’ve just found font-size to be the most bullet-proof.

  • http://www.decalmarketing.com/adwords-book/ Iain Dooley

    Great write-up! This is essentially the principle behind http://www.stacklayout.com/ whilst working with us on http://www.decalcms.com/ @camslice (Campbell McGuinness) started playing with inline-block elements using a fixed-width font to treat “blocks” the same way we treat “text”, but I think the justify alignment isn’t part of that (I didn’t actually create the thing, though and know less about it than Cam does :)

  • Alistair

    Good stuff Patrick. I’ve been looking at using masonry/isotope/packery but we don’t like the extra space it leaves down the right-hand side. Wonder if this technique would work alongside.

    • barrelny

      Hi Alistair,

      Check out mixitup.io for an alternative to Masonry/Isotope that will work with this technique!

  • Joel

    It looks like actual spaces must exist in the html source between the inline-block elements, which rules out compressing your html. Just beware of this. (Or is there a workaround?)

    • barrelny

      Yes that’s correct – if you do want margins, you will need whitespace/line-breaks in the HTML.

    • Jaik Dean

      I just posted this in response to someone else too, but if your HTML minification removes all spaces then it’s at fault, as whitespace has meaning. This is really just highlighting a bug in the minifier rather than a problem with this technique :-)

      • Joel

        That’s a good point, thanks. As I saw you mention elsewhere, replacing whitespace between tags with a single space would be the right thing for HTML minifiers to do.

        As I just posted elsewhere on this discussion, I still feel a bit uncertain about the idea of having the layout dependent on whether the HTML author puts a space between the inline items or not. Third-party libraries/frameworks are sure to get a certain amount of issues opened due to this, for example. I’d be easily swayed by good arguments, though. I want to be!

  • Pingback: Text-align: Justify and RWDdevJerk | devJerk

  • Pingback: Today’s Readings | Aaron T. Grogg

  • Pingback: Text-align: Justify and RWD | BARREL | js bucke...

  • Pingback: Weekly Design News (N.187)

  • http://www.crocodillon.com/ Dillon de Voor

    I thought I was the only one as I’ve been working on the same technique since January, but instead of a placeholder element I would use margins if the total column span doesn’t add up (using back-end processing or JavaScript). I’ve dedicated a website to my findings here: http://justifygrid.com/

    • barrelny

      Hi Dillon – that’s good to know some other people have been experimenting with the same concept! I guess the advantage of the placeholder method is that it is a pure HTML/CSS solution.

      • http://www.crocodillon.com/ Dillon de Voor

        It sure is a clever solution to make life easier. But I’m stubborn and addicted to clean markup. :)

        • Gcyrillus

          hi, what’s dirty about it ?

          • http://www.crocodillon.com/ Dillon de Voor

            That one is still around isn’t it? Not that I’m using it. I’m one of those guys who likes semantic markup, all the markup should have a meaning and be related to content. Keep styling in CSS :)

    • Gcyrillus

      funny, you too hey ;)

  • Godfrey

    Boom. Old school is now the new deal.

    • rickysynnot

      Yeah – Dave Rupert is making coments like this on his Shop Talk Show… in that the web does actually work pretty well on its own, without crazy plugins to achieve these layouts!

  • ulf gjerdingen

    i just dropped everything i was doing. this is so cool!

  • Stephen James

    Thanks. I’m a little scared of the HTML compression/space issue. Here’s a LESS CSS Gist of this, just add inline-blocks. https://gist.github.com/interactivellama/5699885

  • Pingback: Responsive Design Resources

  • Pingback: Grids with text-align: justify

  • timburch

    Fantastic find. Thank Patrick.

  • Pingback: BARREL | Text-align: Justify and RWD

  • Pingback: Grids with text-align: justify | DK Studio

  • Gabe Shackle

    Great technique! One thing I noticed was that the CodePen code uses #Grid::after which I believe does not work in IE8. Switching to just #Grid:after makes it work as expected in IE8.

    • barrelny

      Very true! I realised this too a while ago but forgot to update the pen. It’s now been fixed!

  • Gcyrillus

    Hi,

    Glad to see an article about that, it gives me another reference to say: use it !

    I’v e been using this for years and it is not a hack!

    It worked in IE5.5 (display:inline;zoom:1;)

    that’s the way text and inline-boxes can be styled , no matter if it is a . text-align will do its job.

    display:flex comes and Float is almost(IMHO) dead.

    Nobodies mind if you float or with it :) . What was, or still is, wrong with display ?, maybe i miss some thing.

    It is a case very similar to vertical-centering element width display:inline-block; it worked already with IE5.5(display:inline;zoom:1;), but everyone use to point absolute centering. :) and nobody would want to hear, understand or agree that display:inline-block was, in the flow, a good way.

    (Inline-block (& zoom) has to do with layout., someone remenbers IE6 haslayout ? ;) ).

    Bye the way, it follows direction of your page( dir/direction| rtl/ltr)

    hey, You never see a floatting menu or boxe do so.

    Cheers & thanks for the article.

    • http://www.crocodillon.com/ Dillon de Voor

      Yeah, hasLayout to the rescue :P

      • Gcyrillus

        yep

    • Morgan Huff

      Good suggestion for getting IE to behave! In my tests, everything lte IE7 has collapsed margins between the grid boxes. Any recommendations on how to preserve the spacing between grid elements? Thanks!

      • Gcyrillus

        that’s it :)

  • Sajjad Ahmad

    i just love it and will use every where from now :)

    • http://santiagorojo.com.ar/ Santiago Rojo

      +1

  • Pingback: Text-align: Justify and RWD | timhecker.it

  • David Hidalgo

    You can remove de margin-bottom of .placeholder for remove the extra height when the grid is in 2 rows

  • Pingback: All I don't know

  • leonardteo

    Brilliant!

  • Peter Chon

    omg

    • http://www.frenchtouchseduction.com/ FK

      I did.

      • Mustafa

        me too

  • Pingback: html5 css3 | Pearltrees

  • Pingback: CSS Justify Magic for RWD | WNT Library

  • http://341design.com.au Chris Howard

    I think I want to cry! I spent so many frustrating hours a couple of years back coding PHP to handle all of this…. If only I’d been smartererer back then. :( Maybe I wouldn’t be as grey now.

    I know others say “flexbox can do it”, but it is not fully supported in IE10 and not at all in IE9 or less, so that looks like a whole lotta hurt hacking to multiple solutions.

    I’m not convinced yet flexbox is ready for primetime, but this technique certainly is.

    Well done – but where were you 2 years ago when I really needed this?!

  • Ryan Seddon

    Awesome technique, hacks FTW!

    You could avoid the 0.1px font rule by using letter-spacing: -0.31em; and then a subsequent hack for opera by adjusting word-spacing: -0.43em;

    See @necolas grid as a good example https://github.com/suitcss/grid/blob/master/grid.css#L45

  • Luke Hopkins

    This is going to save me so much time.

    Thanks for sharing.

  • Carl Simmons

    If the total gutter width inside a row is greater than a column width, you end up with more columns than you expected… any way around this?

    • http://www.crocodillon.com/ Dillon de Voor

      Increase letter-spacing to as much as you need (font-size can’t be 0 for this trick). For example for 40px gutter use font-size: 1px and letter-spacing up to 40px, as much as you need.

  • Pete Droll

    Fantastic stuff here. Not having to mess with horizontal margins + percentage widths is a huge plus.
    I was just playing around with this, and came up with a question:

    It seems that if you have the correct number of placeholders (max number of “columns” -2), you don’t really need the additional “break” element as well. Is that true?

    • barrelny

      For a bulletproof layout, you do need the break element in addition to the placeholders.

  • Morgan Huff

    Fantastic solution! Thanks for the write-up.

    In some experiments, I’ve fond ‘text-justify: distribute-all-lines;’ will help IE7 justify the grid elements properly and prevent collapsing of the white-space margins between elements.

  • http://www.DesignYourOwnBlog.com/ Marianne

    you are seriously my hero. i just used this and it worked perfectly the first time. thank you for such a simple trick, i love it, love it, love it!

  • Luke Hopkins

    You mention needing IE7 hacks. What are these?

  • Wout Mager

    I love the technique, but unfortunately it stops working once you minify your html. That’s because the html becomes one line, and the browser stops seeing items as different ‘words’. I haven’t thought of a solution yet, but this is a major disadvantage.

    • Jaik Dean

      I’d argue that your minification is incorrect in this case. Whitespace has meaning in HTML, so rather than removing it all, each “block” of whitespace should be replaced with a single space character.

      • Wout Mager

        But isn’t the standard way to minify html to remove all whitespace?

        • Jaik Dean

          Standard, perhaps, but not correct :-)

          • Wout Mager

            :-) Could you elaborate a bit on the meaning of whitespace? I’ve been building sites for some time now, but this is the first time something broke because of removing whitespace.

          • Jaik Dean

            Whitespace would be any characters such as spaces, tabs or line returns. If you enter a block of text and put multiple spaces or line returns in the middle, they will be rendered as a single space on the site.

            Block-level elements aren’t affected by surrounding whitespace, hence why removing it makes no difference to the layout and is the standard behaviour of most minifiers. However, inline elements (including inline-block) are affected by whitespace, in that any whitespace between two inline-block elements will be rendered as a space character by the browser.

            Minifiers know not to remove spaces in the middle of text, otherwise everythingwouldlooklikethis. However, they don’t know what you’ve applied `display: inline-block` to and so will generally remove all whitespace between elements.

          • Wout Mager

            Great explanation!

          • barrelny

            Very interesting!

    • Christian Z.

      To me minifying HTML isn’t all that important.

      • Wout Mager

        It is to your users.

        • Christian Z.

          What kind of performance increases have you seen from it?

          • Wout Mager

            Google provides a simple explanation on their pagespeed site: https://developers.google.com/speed/docs/best-practices/payload#MinifyHTML

            I agree that it feels like the performance increase is too small to matter, but for me it’s part of providing the best experience possible. It’s one of those things you just do :-)

          • Christian Z.

            I wonder why they didn’t minify their own HTML then.

          • Wout Mager

            Me too. So what’s your point?

        • Ricardo Zea

          Agree with Christian Z.

          Minifying your markup is not THAT important, nor it really interferes that much with the user experience. And I am ALL about the user experience, I’ll tell you that.

          If you’re really that hard core about page performance/optimization, check out “One Less JPG”: http://fourkitchens.com/blog/2013/04/24/one-less-jpg.

          • Wout Mager

            For me, minifying html is just as important as minifying javascript or css. Or using sprites. It’s just one of those things you do. It takes little effort and makes everything just a little faster.

            Interesting article btw, thanks! I’m working on a project now where I intend to use a similar technique. Because I’m that hardcore about page performance :-)

          • Ricardo Zea

            Sprites and HTML minification are done for entirely different technical reasons: Reduce HTTP Requests; Improve page/site performance. Although the first one leads to the second one, but it’s not the main reason, so your comparison is a bit misleading.

            Going back to HTML minification, I totally agree with doing it and have nothing against it, at all, but it’s certainly one of my last to-do items in my list, and if I don’t do it, no big deal, I know I’m not terribly affecting the users’ experience.

            One note though: If anyone is working by themselves and have such control over the markup, the should feel very lucky about it because when you’re working with a large team in which you have in-house and/or off-shore developers that may not understand/care (I still haven’t figured that one out) about even basic performance best practices, HTML minification may very well not be in their vocabulary, hell, not even in their dictionary.

            I’d work with a hardcore page performance developer in a heartbeat, that’s for sure.

        • Joel

          I agree with the pro-HTML minifiers on this thread. Just because it doesn’t provide the same performance benefits as other techniques, it doesn’t mean you shouldn’t consider using it *after* you’ve done everything else. It would be sad if people started using “One Less JPG” as a place to stop looking for further performance gains.

          I also agree with Jaik Dean’s comments about fixing HTML minifiers. If they replaced all whitespace between tags with a single space, that would solve this issue without forcing us to prematurely bin the idea of HTML minification, which—surely even the naysayers can agree—can’t hurt.

          As cool as this technique is—and I’m definitely going to be trying it out more—I’m still not 100% sold on the idea of having the layout dependent on whether the HTML author puts a space between the inline items or not. Third-party libraries are sure to get a certain amount of issues opened due to this, for example. I’d be easily swayed by good arguments, though.

        • http://anentropic.wordpress.com Anentropic

          does minifying achieve anything if the requests are gzipped?

          • http://www.woutmager.nl/ Wout Mager

            I suppose it’s a double win, but I’m not that hardcore into the technical side.

          • http://anentropic.wordpress.com Anentropic

            I wasn’t sure if there’s any point in doing both but it looks like it is a double win after all: http://stackoverflow.com/questions/807119/gzip-versus-minify

          • http://www.woutmager.nl/ Wout Mager

            Nice!

    • Marco Rivadeneyra

      I believe the problem with it being dependant on whitespace, is not only important when using minification, but also when using a framework to create the structure, for example when using angular an ng-repeat directive would create the tags next to each other (no whitespace) which would break this.

      • http://www.woutmager.nl/ Wout Mager

        True. That’s somewhat similar to how I found out this technique needs whitespace.

    • barrelny

      Very interesting arguments/discussion. Personally I’ve never been one to minify my HTML, as I feel like seeing nice, clean, structured, indented source code, is more important to me than the benefits of minification (for HTML), and somehow goes hand in hand with using semantic tags. I always minify my JS though, so perhaps I’m a hypocrite. I’m not anti-minification though, this is just my personal preference.

      • http://www.woutmager.nl/ Wout Mager

        And that’s fine. But why not do both? Only people working with websites care about (or even look at) nice and clean source code :-)

    • http://highrockmedia.com/ High Rock Media

      I’m glad the minification issue was brought up as I just encountered an issue where minification was being done by default to a set of Drupal fields I was theming for use with text-align: justify. I made the mistake of viewing the source code in Chrome web inspector and the HTML markup looked fine. Then in the back of my mind, I remembered this thread so I then looked at the actual HTML source and sure enough that part of it was minified. Now all I had to do was create a custom template override and job done.

  • Pingback: Grids with text-align: justify | typography | S...

  • Pingback: IT Digest: Computex 2013, Making WebGL Dance, CSS: Reset or Normalize, Digital Trends and Much More! | Zfort Group Blog

  • Pingback: Новости » Blog Archive » Дайджест интересных материалов из мира веб-разработки и IT за последнюю неделю №60 (1 — 8 июня 2013)

  • Pingback: Responsive Design Weekly #59 | Responsive Design Weekly

  • Pingback: Today’s Readings | Aaron T. Grogg

  • Pingback: Best of JavaScript, HTML & CSS – Week of June 3, 2013 | Flippin' Awesome

  • Pingback: Responsive CSS technique for horizontal spacing | web developer wall

  • http://bittersmann.de/ Gunnar Bittersmann

    This hack would have been unnecessary for ages if only …

    IE introduced the text-align-last property; it was specced in CSS 2.0, removed from CSS 2.1 due to lack of implementation in other browsers (shame on you, vendors), and has its comeback in the CSS3 Text module. http://www.w3.org/TR/css3-text/#text-align-last

    Now it’s also implemented in Chrome and as -moz-text-align-last in Firefox, it’s not implemented in Safari and Opera (Presto).

    I once came up with a cross-browser solution in http://forum.de.selfhtml.org/archiv/2011/3/t204093/#m1381675

    • barrelny

      Wow very interesting!

  • Pingback: google

  • Pingback: Fusion Radar: June 12, 2013 | Agency Fusion Blog

  • Pingback: can't seem to make the menu centered(wordpress) - DesignersTalk

  • Pingback: Barrel Intern Blog | Our Process

  • Pingback: Responsive Webdesign Tipp: Fluid Grid mit CSS Text-Align | tutorialbox.de

  • Pingback: WordPress attached images gallery | karine.do/writes

  • Pingback: Weekly Link Digest : HTML/CSS | Blog MNCC

  • Pingback: Text-align: Justify and RWD | BARREL | Responsi...

  • Pingback: Text-align: Justify and RWD | Webdesign & G...

  • Pingback: Tweet Parade (no. 26 June 2013) - Best Articles of Last Week | gonzoblog

  • http://lou.pe/ Philip Meissner

    Wow. Looks like we have a sequel to the Paul Irish blockbuster * { box-sizing: border-box } FTW

    text-align: justify; FTW II

  • Mattijs Spierings

    Hi,

    I am still having an issue with IE7 : the LI’s do not have any horizontal margin between them.

    See fiddle: http://jsfiddle.net/LLvQB/
    Anyone a clue how to fix this?

    • http://www.crocodillon.com/ Dillon de Voor

      Allow me :-) Read the CSS comments.

      http://jsfiddle.net/LLvQB/2/

      • Mattijs Spierings

        Thanks. The zoom: 1 on the grid was the missing link. I remember trying that yesterday but maybe I did something else too.
        Anyway thanks for clearing this up. Nice methology to have.

  • Pingback: Text-align: Justify and RWD | BARREL | UX Desig...

  • Pingback: Technique | Pearltrees

  • amit

    Thanks for the great article. I have a small problem though. I need to make my surrounding borders overlap for listitems. This would give more clarity. KIndly help if possible.
    http://jsfiddle.net/aAkAK/

    • barrelny

      Hi Amit -

      I’ve forked your fiddle – is this the behaviour you are looking for? http://jsfiddle.net/drQvS/1/

      Couple of important things to notice:
      - Font-size 0.1px on the <ul>
      - box-sizing: border-box on the <li>s
      - width of 20% and text-align: center on the <li>s

      By the way – text-align: justify is not necessary for this example, but inline-block is. The basic principal is the same however.

      • amit

        Thanks a lot. This seems to work well.

  • Pingback: Overlap surrounding borders in listitems while using css property of "text-align:justify" to make my site responsive | BlogoSfera

  • Peter

    Ha, this is funny. I used this technique exactly 1 1/2 years ago for my very first responsive project. Great roundup!

  • http://jareddesign.com Jared Christensen

    Great discovery, this has saved my butt a few times now!

  • Pingback: 財布 miumiu

  • Pingback: prada サングラス

  • Pingback: 10 improbable CodePens | Information Bites

  • Pingback: Text-align: Justify and RWD | Responsive design...

  • Pingback: Text-align:Justify和RWD | 易资讯

  • Pingback: Text-align: Justify and RWD | Responsive Web De...

  • Pingback: CSS 分散對齊橫列選單項目 « WMの物語

  • Pingback: Quick Films Can Be Great

  • Pingback: Perfectly Aligned Navigation with CSS | Maddness Media

  • Pingback: car title loans

  • Pingback: car title loans los angeles

  • Pingback: notary public

  • Pingback: auto loans

  • Pingback: online universities

  • Pingback: Text-align: Justify and RWD | Multipop

  • Pingback: o canada french

  • Pingback: o canada french

  • Pingback: Perfectly Aligned Navigation with CSS - How To Tricks

  • Pingback: CSS 奇技淫巧十八招 « WMの物語

  • Pingback: malware removal

  • Pingback: Watch Perfectly Aligned Navigation with CSS

  • Pingback: cheap eyeglasses

  • Pingback: bankruptcy information

  • Pingback: title loans tulsa ok

  • Pingback: bankruptcy chapter 7

  • Pingback: chapter 13 bankruptcy

  • Pingback: filing bankruptcy

  • Pingback: chapter 11 bankruptcy

  • Pingback: bankruptcy forms

  • Pingback: bankruptcy lawyer

  • Pingback: Advanced RWD layout techniques | Amazing WordPress

  • Pingback: Text-align: Justify and RWD | BARREL – Lindsey Austinson

  • Pingback: Google free instagram followers

Popular This Week
Text-align: Justify and RWD
March 12, 2013

Text-align: Justify and RWD

By Patrick Kunka
Taking Control of Image Loading
July 29, 2013

Taking Control of Image Loading

By Patrick Kunka
5 Blind Spots to Consider When Designing Web Apps
July 31, 2014

5 Blind Spots to Consider When Designing Web Apps

By Yvonne Weng
Members-Only for WordPress, Part 1: User Roles
January 15, 2014

Members-Only for WordPress, Part 1: User Roles

By Wes Turner

Like what you’re reading? Sign up for the Barrel newsletter and receive updates.