Ignore whitespace in HTML

102,336

Solution 1

Oh, you can really easy accomplish that with a single line of CSS:

#parent_of_imgs { white-space-collapse: discard; }

Disadvantage, you ask? No browser has implemented this extremely useful feature (think of inline blocks in general) yet. :-(

What I did from time to time, although it's ugly as the night is dark, is to use comments:

<p><!--
  --><img src="." alt="" /><!--
  --><img src="." alt="" /><!--
  --><img src="." alt="" /><!--
  --><img src="." alt="" /><!--
--></p>

Solution 2

you can set the font-size of the container to 0 and the white-space disappears!

Solution 3

The browsers does ignore whitespace in most cases when it's next to a block element.

The problem with images (in this case) is that they are inline elements, so while you write them on separate lines, they are actually elements on the same line with a space between them (as the line break counts as a space). It would be incorrect for the browser to remove the spaces between the images, writing the image tags with line breaks between them should be handled the same way as writing the image tags on the same line with spaces between them.

You can use CSS to make the images block elements and float them next to each other, that solves a lot of problems with spacing, both the space between the images and the spacing on the text line below images.

Solution 4

The newest solution for this is using display: flex on outside container, you can try this with following example:

Codepen →

(And yes, Flexbox is becoming widely supported: http://caniuse.com/#search=flexbox)

HTML:

<!-- Disregard spaces between inline-block elements? -->
<div class="box">
  <span></span>
  <span></span>
  <span></span>
</div>

CSS

.box {
  display: flex;
  display: -webkit-flex;    
}

span {
  display: inline-block;
  width: 30px;
  height: 30px;
  background-color: #fcf;
  border: 2px solid #f9f;
}

Update: Also, if you want your items to wrap (as standard inline-block elements do), don't forget to add flex-wrap: wrap to your flexbox container.

Solution 5

Unfortunately, newlines count as space characters.

The best solution I have come up with is to use the whitespace inside the tags themselves, instead of outside:

  <img src="images/minithing.jpg" alt="my mini thing" 
/><img src="images/minithing.jpg" alt="my mini thing"
/><img src="images/minithing.jpg" alt="my mini thing"
/><img src="images/minithing.jpg" alt="my mini thing" />

It's not ideal, either, I know. But at least it's not some bizarre CSS hack that relies on the size a space character is rendered or resorting to relative positioning, or JavaScript :)

Share:
102,336

Related videos on Youtube

Paul
Author by

Paul

ASP.Net, C# developer currently in Cambridge, England. I'm up for any challenge, and really enjoy working with other people to build out new ideas Since leaving full-time employment, my main focus is now Intelligent Penguin and working with many other developers, designers and small businesses, providing lots of on-line services.

Updated on October 20, 2020

Comments

  • Paul
    Paul over 3 years

    Is there anything in HTML/CSS that tells the browser to ignore whitespace completely?

    So many times when you want to put, say, two images next to each other - you try desperately to keep the HTML readable, but the browser puts a space between them.

    So instead of something like this:

    <img src="images/minithing.jpg" alt="my mini thing" />
    <img src="images/minithing.jpg" alt="my mini thing" />
    <img src="images/minithing.jpg" alt="my mini thing" />
    <img src="images/minithing.jpg" alt="my mini thing" />
    

    you end up with this

    <img src="images/minithing.jpg" alt="my mini thing" /><img src="images/minithing.jpg" alt="my mini thing" /><img src="images/minithing.jpg" alt="my mini thing" /><img src="images/minithing.jpg" alt="my mini thing" />
    

    Which is just so horrible!

    • BalusC
      BalusC about 14 years
      Unrelated to the problem: there's a subtle difference between HTML and XHTML. You're talking about HTML, but posting XHTML code (in HTML the img tag is a shorttag).
    • ktamlyn
      ktamlyn over 11 years
      See my answer in this question for a full set of options relevant now: stackoverflow.com/questions/14630061/…
    • Roland Dercsényi
      Roland Dercsényi about 11 years
      display: table-cell works great in all the browsers I've tested.
    • Lee Goddard
      Lee Goddard almost 10 years
    • Josh M.
      Josh M. about 9 years
      This has got to be one of the most annoying issues us web developers/designers come across. I can't believe it hasn't been fixed yet, for real.
    • Dan Bray
      Dan Bray over 6 years
      Use letter-spacing: -0.31em; to remove the whitespaces.
    • Tom Doodler
      Tom Doodler over 6 years
      For people experiencing this issue with Angular 5: See preserveWhitespaces: softwarearchitekt.at/post/2017/08/31/…
  • Paul
    Paul about 14 years
    Hm, I was afraid of this. I really hope this isn't going to be another case of some javascript hackery to make HTML actually work
  • GeeF
    GeeF about 14 years
    I don't think the question has anything to do about block/inline elements. I think the asker is wonder why his HTML looks like that when viewing the page source, not how they appear on the page.
  • user1877401
    user1877401 about 14 years
    I think using CSS to hack around something that can be very easily fixed in the HTML source is overkill and likely to cause you problems in any complex layout. It also doesn't degrade well.
  • Guffa
    Guffa about 14 years
    @Lee: Sorry, you got it wrong. (See IP's answer to Matts comment to your answer.)
  • Guffa
    Guffa about 14 years
    @Jon: It's not about "hacking around" something. The layout should preferrably be controlled by the CSS, so specifying how the images are displayed should actually rather be in the CSS than in the HTML.
  • Warty
    Warty about 14 years
    Although I find the commenting way horrifyingly ugly, I use it. Just make it so your IDE displays the comments in a light color so its not "in your face" =P
  • user1877401
    user1877401 about 14 years
    It is hacking if you have to float the images (what if they are inline with something else? now you have to float everything. what if there is already something else floated? now you have to break the semantic layout of your page to deal with it) or use relative positioning that relies on the size a space character is rendered.
  • Guffa
    Guffa about 14 years
    @Jon: What's with you and "hacking"? Floating the images is one way of solving the problem that works in some situations. I have neither said that it's the only solution nor that it is always applicable.
  • Evan Carroll
    Evan Carroll almost 14 years
    that seems especially scary as it requires re-rendering the entire wrapper.
  • Evan Carroll
    Evan Carroll almost 14 years
    Where did you get the idea that image is some sort of blank, and alt is the method of filling it in to make a grammatically and punctually correct sentence, rather than alt being a short description of the image?
  • fuxia
    fuxia almost 14 years
    By listening in JAWS and browsing without images.
  • system PAUSE
    system PAUSE over 13 years
    I've also used this, although it does cause some weaker HTML tools to barf horribly. (Not so much XHTML.)
  • Spudley
    Spudley about 13 years
    +1. It's a horrible hack, but it works, and seems like the best solution in the absence of support for the white-space-collapse style. (but note: if you have text in the child elements, you also need to set the font size back to normal again for them, or all your content will vanish)
  • ysth
    ysth almost 13 years
    Apparently that property has been renamed a lot; as of now, the page says "Major Changes...February 2011...Renamed ‘white-space-collapsing’ to ‘bikeshedding’."
  • ysth
    ysth almost 13 years
    And later css working group minutes say it will be text-space-collapse.
  • gsteinert
    gsteinert almost 13 years
    You also lose the ability to use percentages for font sizes as they are calculated as a percentage of the parent container (which will be 0)
  • yunzen
    yunzen over 12 years
    CSS would be text-space-collapse:trim-inner with latest changes in specification
  • Camilo Martin
    Camilo Martin almost 12 years
    Actually, maybe you're right about minifying the HTML. +1. (I can't understand what @Evan is talking about)
  • Drew Noakes
    Drew Noakes almost 12 years
    Way to get my hopes up for doing this in CSS! BTW it seems that the anchor in the doc you're linking too has gone. Perhaps it's been removed from the CSS3 standard.
  • Drew Noakes
    Drew Noakes almost 12 years
    @yunzen, it looks like even that property has been removed from the spec.
  • Boldewyn
    Boldewyn almost 12 years
    It has moved to level 4, dev.w3.org/csswg/css4-text/#white-space-collapsing, which means far future for us :-(
  • mhenry1384
    mhenry1384 over 11 years
    Interestingly, this works in Chrome but not Safari (tested Chrome 22, Safari 5.1.7). It works in Safari if you specify a height of 1px.
  • Josh Mouch
    Josh Mouch over 11 years
    While this has the potential to "cancel" out nested font sizes, this is my favorite solution.
  • brunoais
    brunoais about 11 years
    not good. Those properties are inherited...
  • hasen
    hasen about 11 years
    I think that good minifier should (by definition) not introduce semantic changes to the document through the process of minification. So if your minifier currently removes whitespace, watch out when they "fix" that bug.
  • Fitzchak Yitzchaki
    Fitzchak Yitzchaki about 11 years
    I agree that it should not make semantic changes. Yes.
  • Blazemonger
    Blazemonger about 10 years
    One thing you can do with inline-block that you can't do with table-cell: align all the elements to the right or center by setting text-align on the parent.
  • Blazemonger
    Blazemonger about 10 years
    A smart minifier should not remove the spaces in this case because they might be desirable in some cases when using inline-block.
  • Blazemonger
    Blazemonger about 10 years
    @brunoais Yes, the only caveat of this technique is that you have to explicitly reset the font-size on child elements.
  • Robert Siemer
    Robert Siemer almost 10 years
    Interesting insight. I think this underlines the true cause to this problem: Images are default inline. If you don't use images as inline elements, make sure to declare them as something blocky.
  • Justo
    Justo almost 10 years
    Best option for legitimacy. Not supported in IE<7. Any way, you can use style conditionals for IE.
  • rsp
    rsp almost 10 years
    +1 for a style that I invented in the nineties. ;) I'm sure I wasn't the first one to do it (and I didn't use the slashes because there was no XHTML back then) but it was a routine way of writing HTML in days when I had a lot of images that had to be perfectly aligned with no gaps. :) I still sometimes do it because I don't like having text nodes where there shouldn't be any and I don't think CSS is good for removing things from the DOM that shouldn't be there in the first place. Having whitespace written in a 0px font is not the same - it's like 1px transparent GIFs - but backwords.
  • Cool Blue
    Cool Blue almost 10 years
    But it should remove newline characters because they are not rendered faithfully.
  • Yarin
    Yarin over 9 years
    Flexbox FTW- See here, here, here, and here,
  • commonpike
    commonpike over 9 years
    This is the 'correct' answer, its just bit big. The browser shows spaces because the images are displayed in line with the text. If you dont want that, say display:block or something else, like table-cell, in css.
  • Rich B
    Rich B about 9 years
    Setting white-space: nowrap; on the parent container worked for me recently.
  • Boldewyn
    Boldewyn about 9 years
    @RichB how that? Did you have white space between your tags?
  • Rich B
    Rich B about 9 years
    @Boldewyn Yes, in the editor I was using I had new lines and tabs between tags in order to prettify my html and make it more readadble.
  • Fred Gandt
    Fred Gandt about 9 years
    I nearly answered this the same way, but thought to check - and lo! - it's right at the bottom :-( Voted up of course, although, suggestion: "...before it's SENT to the browser...".
  • jairhumberto
    jairhumberto about 9 years
    when you're using em unit this solution doesn't work either. But you can use rem unit (widely implemented) instead. I think rem unit is more practical. then you could use font-size 0 as far as you needed
  • Jonathan Cross
    Jonathan Cross almost 9 years
    This did nothing in my case, but using display: table on the parent element worked in Chrome 44.
  • Brain2000
    Brain2000 over 8 years
    This doesn't work if you display:none then later display:block your element. It will add the carriage return when it is displayed again.
  • Crystal Miller
    Crystal Miller about 8 years
    Flex is not widely supported. You are fooled by the amount of green on the caniuse page. It is not supported by Safari Versions before Safari 9 nor on older iPads or older iPhones.
  • Crystal Miller
    Crystal Miller about 8 years
    1) This does not work with Safari. 2) If you are not using px to define your site which now days is more likely than not), this can really mess up the content.
  • ted451
    ted451 about 8 years
    @CrystalMiller this depends on your definition of 'widely' of course. I consider 94%+ to be 'wide enough'. Your case may be different. I did not say it is supported by 100% of browsers.
  • Crystal Miller
    Crystal Miller about 8 years
    While I agree it does depend on what you need to support, I wouldn't say the support for flex is quite 94%, as it is not supported by any of the old Safari versions (Mobile or Desktop) nor IE (until 11 & virtually no IE user is using IE11) & only certain versions of Firefox. I use flex in some portions of my site & I found that a large portion of my users are not seeing the site flex.
  • Philip Helger
    Philip Helger almost 8 years
    According to caniuse.com/#search=table-cell it can be used in all browsers except IE 6+7. So it should work in IE8 as well.
  • Dunnow
    Dunnow over 7 years
    margin-right: -4px; this would've solved it in a nicer way
  • Boldewyn
    Boldewyn over 7 years
    If the user's font in the current font size happens to feature a space exactly 4px wide, yes. If not, you'll get funny notices from your customer.
  • Dariusz Walczak
    Dariusz Walczak over 7 years
    Rolled back to the original answer because this weird formatting was the actual solution.
  • c24w
    c24w over 7 years
    You can restore the font-size for child elements of the container using something like #container > * { font-size: initial; }.
  • Nilloc
    Nilloc about 7 years
    font-family:monospaced; margin-right:-1ch; img:last-child{margin-right:0;} if I had do to it that way.
  • Victor Zamanian
    Victor Zamanian over 4 years
    drafts.csswg.org/css-text-4/#propdef-text-space-trim is the current property I believe.
  • Boldewyn
    Boldewyn over 4 years
    Thanks! If I understand the spec correctly, we’d need more than a single line, though. Especially we’d need to text-space-trim: discard-before all images. Sigh.
  • Matt Montag
    Matt Montag over 2 years
    Great solution. If you have to support pre-flexbox, my heart goes out to you.
  • Matt Montag
    Matt Montag over 2 years
    I have downvoted because there are much better solutions now.
  • Matt Montag
    Matt Montag over 2 years
    I've downvoted because there are better solutions now. Stackoverflow is meant to evolve :)
  • Tomalak
    Tomalak over 2 years
    Not to forget display: inline-flex;, for situations where you have multiple containers on a line.