Aditya Bhave
Aditya Bhave

Reputation: 1028

White space removed by minifier tools affects look and feel of HTML

We usually add white spaces in HTML to make readable

Example – Development Version:

<div>
    <span class="surround-brackets">
        Title
    </span>
</div>

When above code is minimized (for prod build), we get following output

<div><span class="surround-brackets">Title</span></div>

Now, consider we have a pseudo elements added to class “surround-brackets”. Following is the CSS

.surround-brackets::before {
    content: "(";
}

.surround-brackets::after {
    content: ")";
}

Please check fiddle here - Fiddle

Any suggestions how to avoid such issues ?

Upvotes: 4

Views: 2170

Answers (1)

Lee Kowalkowski
Lee Kowalkowski

Reputation: 11751

It's possible to minify JavaScript and CSS without adversely modifying meaning or behaviour. This is frequently not true for HTML.

<span> is phrasing content, which means spaces are significant. It's actually incorrect for a HTML minifier to remove any space from within phrasing content, because you may want a CSS rule like white-space:pre.

Strictly, the minifier should output:

<div><span class="surround-brackets">
        Title
    </span></div>

Even if your minifier was aware of the CSS (which it shouldn't be, you can apply multiple CSS files to the same HTML), it should collapse runs of whitespace in phrasing content, but not strip them:

<div><span class="surround-brackets"> Title </span></div>

...the effective minified equivalent assuming normal CSS white-space processing.

You could preserve any wanted spacing in phrasing content by using &#32; everywhere you intentionally want a leading or trailing space, but from a maintenance point of view, I think that might be a lot of effort.

Minification of HTML is probably not important compared to using gzip. Safe minification of HTML does not save much bandwidth, about 5%. Unsafe minification may save up to 25%. Gzip is much better and usually saves at least 80%.

Upvotes: 5

Related Questions