Inexplicable HTML / CSS Behavior

I have a simple html page with pretty simple css , and it drives me crazy - I don’t understand what is going on here (the original task is to create a simple contact form using modernizr, but I lost everything):

<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> 

Three lines with labels and input fields increase the left margins, and if I set the focus to any input, those below will go back (at least in Chrome and FF). Why?

Now, if I remove almost any css property, things get weirder:

  • The original above can be found here .
  • If I delete the body line (or even just the line height: 26px; part !! ), the left margin disappears (why?), Check here .
  • If I remove the input: the focus line, the transition will no longer occur (why?), Check here .
  • If I remove the border: 1px solid #ccc; from the input, the fields are gone (why ???), check here .

And there are other interdependencies. This does not happen in jsfiddle and other online tools, but can be easily played locally.

Bottom line: all the behavior seems completely alien to me, and I hope that Sherlock Holmes CSS can shed light on what is happening here.

+4
source share
2 answers

The problem with the numbered list.

You set the top edge and make the line height larger than the text itself. This is usually normal, but it makes the numbers larger than the input fields.

You force a new line with <br /> , and they cannot normally float to where they should be, since the previous number is "too large" for its "line".

I'm struggling to explain this, but to fix this you can add line-height: 2; into the input fields or any corrections you mentioned, or even better, replace all of this with an ordered list.

If you still do not understand, try setting border: 1px solid #000; on the shortcuts, you will see what I mean.

+3
source

The unexpected behavior is due to the fact that labels act in the same float context without breaking its clear . Therefore, when you point your second label to the float on the left, it finds the previous label and thus "stacks" to the right.

Add the following to your CSS (if you insist on using br tags):

 br { clear: both; } 
+2
source

All Articles