How Do I Avoid Line-Break Padding?
Asked Answered
S

4

7

My biggest gripe with HTML is that line breaks add a tiny bit of space between elements. (jsFiddle.)

This can screw up layouts where child elements are sized to exactly fit their parents.

I read somewhere that you can remove this implicit padding - while still keeping the code somewhat legible - by using comments like this:

<!--
--><div>Foo</div><!--
--><div>Bar</div><!--
--><div>And so on...</div><!--
-->

This works, but I feel like there has to be a better solution. What other ways are there to work around the line-break padding?

Sidelong answered 25/8, 2011 at 6:6 Comment(1)
I also found this related question where various users found other workarounds.Yerxa
T
4

That isn't "a little bit of space", but literally a space character. You are using display: inline-block to align your elements horizonally, and that's how "inline" works.

If you want to use inline-block you need to remove the white space between the elements as you are doing it.

Otherwise you can use one of the other methods to horizontally align, for example floating or display: table-cell.

Teriann answered 25/8, 2011 at 8:51 Comment(0)
Y
1

A solution would be to use some HTML compressor before publishing your pages to remove unneeded space from your markup, like in this example.

From what I've seen though, they tend to leave always one space at least, because they don't know if you really wanted that space or not, and since browsers considers only the first space if there are more than one, compressors leave one space there.

Yerxa answered 25/8, 2011 at 6:57 Comment(2)
I guess I could always make my own script/program to strip all unquoted whitespace, if I really needed to. It's not a particularly difficult thing to implement.Sidelong
Yes that's also what I'm planning to do as soon as I've some spare time. It's just some big text manipulation, not a big thing really. So you can customize it with your options depending on the situation.Yerxa
A
1

You should try font-size:0px; line-height:0px for outer div.

Something like this:

<div class="outer">
  <div class="inner">123</div>
  <div class="inner">34556</div>
</div>

<style>
.outer {
  font-size:0px;
  line-height:0px;
}

.inner {
  font-size:14px;
  line-height:16px;
  display:inline-block;
}
</style>
Abstraction answered 25/8, 2011 at 8:41 Comment(0)
C
1

This is because you use display: inline-block; for the div elements.

Block elements strip white space around them, inline elements don't.

Try float: left; instead.

Clam answered 25/8, 2011 at 8:50 Comment(2)
Somehow, using floats seems even less elegant than stuffing the line breaks in comments.Sidelong
It's not less elegant, it's differently dangerous. If you use comments, chances are that you're commenting too much. Floats are fragile when used in layouts and the window width changes too much.Clam

© 2022 - 2024 — McMap. All rights reserved.