I have a simple html page with a rather simple css, and it drives me nuts – I do not at all understand what is happening here (the original task is to create a simple contact form, using modernizr, but I have stripped everything down):
<html>
<head>
<style>
body {
font-size: 16px;
line-height: 26px;
}
label {
float: left;
margin-top: 4px;
}
input {
border: 1px solid #ccc;
margin: 4px;
}
input:focus {
border: 2px solid #900;
}
</style>
</head>
<body>
<label>1:</label><input id="1" /><br />
<label>2:</label><input id="2" /><br />
<label>3:</label><input id="3" /><br />
</body>
</html>
The three rows with the labels and the input boxes have increasing left margins, and if I set the focus to any input, the ones below jump back (at least in Chrome and FF). Why?
Now, if I remove virtually any css property, things get stranger:
- The original above can be found here.
- If I remove the the body line (or even only the line-height: 26px; part!!), the left margin disappears (why?), check here.
- If I remove the input:focus line, the jump doesn’t happen anymore (why?), check here.
- If I remove border: 1px solid #ccc; from input, the margins are gone (why???), check here.
And there are other interdependencies as well. This doesn’t happen in jsfiddle and other online tools but can be easily reproduced locally.
Bottom line: the whole behavior seems completely alien to me, and I hope a CSS Sherlock Holmes can shed some light on what happens here.
The problem is with the numbered list.
You are setting a margin-top, and making the line height bigger than the text itself. This is normally fine but this makes the numbers bigger than the input boxes.
You are forcing a new line with
<br />and they can’t naturally float to where they should be, as the previous number is “too large” for its “line”.I’m struggling to explain it, but to fix it you can add
line-height: 2;to the input boxes, or any of the fixes you mentioned, or better yet replace it all with an ordered list.If you still don’t understand, try setting
border: 1px solid #000;on the labels, you will see what I mean.