J.Joe J.Joe - 6 months ago 9
HTML Question

What does <br/> do exactly?

Can anyone explain what

<br />
does to the page? The result is unexpected.
I tested the code on the latest version of Chrome and Firefox, the result is the same on both browsers. So there must be some explanation to this.
I am not trying to do a clearfix. I am just curious how it happened.

<br/>
used with
position:absolute;
:



.box{
position: absolute;
padding:1em;
border:1px solid black;
}

<div class="box"></div>
<br/>
<div class="box"></div>





<br/>
used with
float:left;
:



.box{
float:left;
padding:1em;
border:1px solid black;
}

<div class="box"></div>
<br/>
<div class="box"></div>




Answer

As mentioned, the br element introduces a line break. How exactly this element is implemented in CSS varies greatly across browsers, but as you're dealing with two block-level boxes, I'm not surprised the behavior is consistent here.

The difference in behavior between floating and absolute positioning is that floats never intersect with each other normally (unless you force them to, using negative margins), whereas absolutely positioned elements can intersect because they're not aware of one another (and neither is the rest of the layout).

But note that position: absolute by itself does not change an element's static position (i.e. where it would otherwise be if it wasn't absposed). See the following questions:

This is why the br affects the layout of the second absolutely positioned element. If you hide the first element, it becomes much clearer that the br is just starting on the first line of the document, unaware of the first element, but the second element is aware of the br:

.box {
  position: absolute;
  border: 1px solid black;
  padding: 1em;
}

.box:first-child {
  visibility: hidden;
}
<div class="box"></div>
<br>
<div class="box"></div>

As for floats, the CSS2.1 spec says that floating elements cannot be higher than the line box containing the box of a preceding element. I'm guessing that the br generates an inline box that lives in a new line box, rather than at the end of the previous line (as you would expect of a carriage return), which is why the second floating element starts at the second line of the document rather than the first line.