Ignore whitespace in HTML
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:
(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 :)
Related videos on Youtube
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, 2020Comments
-
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 about 14 yearsUnrelated 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 over 11 yearsSee my answer in this question for a full set of options relevant now: stackoverflow.com/questions/14630061/…
-
Roland Dercsényi about 11 yearsdisplay: table-cell works great in all the browsers I've tested.
-
Lee Goddard almost 10 yearsAll options are covered here: css-tricks.com/fighting-the-space-between-inline-block-elements
-
Josh M. about 9 yearsThis 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 over 6 yearsUse
letter-spacing: -0.31em;
to remove the whitespaces. -
Tom Doodler over 6 yearsFor people experiencing this issue with Angular 5: See
preserveWhitespaces
: softwarearchitekt.at/post/2017/08/31/…
-
-
Paul about 14 yearsHm, 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 about 14 yearsI 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 about 14 yearsI 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 about 14 years@Lee: Sorry, you got it wrong. (See IP's answer to Matts comment to your answer.)
-
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 about 14 yearsAlthough 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 about 14 yearsIt 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 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 almost 14 yearsthat seems especially scary as it requires re-rendering the entire wrapper.
-
Evan Carroll almost 14 yearsWhere did you get the idea that
image
is some sort of blank, andalt
is the method of filling it in to make a grammatically and punctually correct sentence, rather thanalt
being a short description of the image? -
fuxia almost 14 yearsBy listening in JAWS and browsing without images.
-
system PAUSE over 13 yearsI've also used this, although it does cause some weaker HTML tools to barf horribly. (Not so much XHTML.)
-
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 almost 13 yearsApparently that property has been renamed a lot; as of now, the page says "Major Changes...February 2011...Renamed ‘white-space-collapsing’ to ‘bikeshedding’."
-
ysth almost 13 yearsAnd later css working group minutes say it will be text-space-collapse.
-
gsteinert almost 13 yearsYou 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 over 12 yearsCSS would be
text-space-collapse:trim-inner
with latest changes in specification -
Camilo Martin almost 12 yearsActually, maybe you're right about minifying the HTML. +1. (I can't understand what @Evan is talking about)
-
Drew Noakes almost 12 yearsWay 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 almost 12 years@yunzen, it looks like even that property has been removed from the spec.
-
Boldewyn almost 12 yearsIt has moved to level 4, dev.w3.org/csswg/css4-text/#white-space-collapsing, which means far future for us :-(
-
mhenry1384 over 11 yearsInterestingly, 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 over 11 yearsWhile this has the potential to "cancel" out nested font sizes, this is my favorite solution.
-
brunoais about 11 yearsnot good. Those properties are inherited...
-
hasen about 11 yearsI 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 about 11 yearsI agree that it should not make semantic changes. Yes.
-
Blazemonger about 10 yearsOne thing you can do with
inline-block
that you can't do withtable-cell
: align all the elements to the right or center by settingtext-align
on the parent. -
Blazemonger about 10 yearsA smart minifier should not remove the spaces in this case because they might be desirable in some cases when using
inline-block
. -
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 almost 10 yearsInteresting 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 almost 10 yearsBest option for legitimacy. Not supported in IE<7. Any way, you can use style conditionals for IE.
-
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 almost 10 yearsBut it should remove newline characters because they are not rendered faithfully.
-
Yarin over 9 years
-
commonpike over 9 yearsThis 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, saydisplay:block
or something else, like table-cell, in css. -
Rich B about 9 yearsSetting
white-space: nowrap;
on the parent container worked for me recently. -
Boldewyn about 9 years@RichB how that? Did you have white space between your tags?
-
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 about 9 yearsI 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 about 9 yearswhen 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 almost 9 yearsThis did nothing in my case, but using
display: table
on the parent element worked in Chrome 44. -
Brain2000 over 8 yearsThis 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 about 8 yearsFlex 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 about 8 years1) 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 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 about 8 yearsWhile 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 almost 8 yearsAccording 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 over 7 yearsmargin-right: -4px; this would've solved it in a nicer way
-
Boldewyn over 7 yearsIf 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 over 7 yearsRolled back to the original answer because this weird formatting was the actual solution.
-
c24w over 7 yearsYou can restore the font-size for child elements of the container using something like
#container > * { font-size: initial; }
. -
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 over 4 yearsdrafts.csswg.org/css-text-4/#propdef-text-space-trim is the current property I believe.
-
Boldewyn over 4 yearsThanks! 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 over 2 yearsGreat solution. If you have to support pre-flexbox, my heart goes out to you.
-
Matt Montag over 2 yearsI have downvoted because there are much better solutions now.
-
Matt Montag over 2 yearsI've downvoted because there are better solutions now. Stackoverflow is meant to evolve :)
-
Tomalak over 2 yearsNot to forget
display: inline-flex;
, for situations where you have multiple containers on a line.