SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: span inside div

  1. #1
    SitePoint Member
    Join Date
    Oct 2005
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    span inside div

    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, or the <span></span> tags from the HTML, and the display is totally different, with the second paragraph pushed down the page and displaying a full 2ems below the number.

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

    -ct

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When you set position:absolute for an element, it is removed from the document flow. That means it doesn't take up any space, as far as subsequent elements are concerned. Think of it as if the absolutely positioned box is lifted up out of the page, and the content that comes after it slides into the place it would otherwise have occupied.

    Since that SPAN is the only content of the DIV with class="comment", removing the SPAN from the flow leaves the DIV empty. Therefore it doesn't take up any space either – its height will be 0.

    If you remove position:absolute, the SPAN will render inside the DIV and the DIV will have a height that corresponds to one line-height. DIVs are block-level elements, generating block-level boxes, so the paragraph that follows will be pushed down to the next line.
    Birnam wood is come to Dunsinane


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •