PDA

View Full Version : span inside div



c.telarico
15 Jan 2008, 03:47 PM
Consider the following HTML:

<head>
<style>
#chapter {
margin-left:40px;
}

p {
margin-bottom: 2em;
}

.comment {
position: relative;
left: -25px;
}

.number {
position: absolute;
}
</style>
</head>

<body>
<div id="chapter">
<p>
paragraph one
</p>

<div class="comment"><span class="number">4</span></div>
<p>
paragraph two
</p>
</div>
</body>

This will display two paragraphs of text, and the number '4' will appear 25px to the left of the first line of the second paragraph, which is what I want. Now, remove the "position:absolute" style from the span, and the display is totally different, the second paragraph is pushed down the page and displays a full 2ems below the number.

Why does the positioning of the span inside the div change this? I would really like to understand this.

-ct

Wickham
16 Jan 2008, 12:52 AM
Position: absolute means that the element is taken out of the normal flow of the document and is completely isolated from what comes before and after; that is why you can use it to layer over something else. So as far as the <p>paragraph two</p> is concerned, the span tag doesn't exist so the p tag will be as high in <div class="content"> as it can go.


When you remove the position: absolute the <span class="number">4</span> creates another character height plus any default top or bottom margin in the normal flow of the document, pushing down the <p>paragraph two</p> to a lower position.

Edit:- if you add background colors temporarily you will see what is happening; try it with and then without position: absolute in the .number style.

<style type="text/css">
#chapter {
margin-left:40px;
}

p {
margin-bottom: 2em;
}

.comment { background-color: pink;
position: relative;
left: -25px;
}

.number {
position: absolute; background-color: skyblue;
}
</style>
</head>

<body>

<div id="chapter">
<p>
paragraph one
</p>
<div class="comment"><span class="number">4</span></div>
<p style="background-color: green">
paragraph two
</p>
</div>