Luke Lee
Luke Lee

Reputation: 33

there is an odd css issue, the text inside a div did not move with the div

Guys

I have a simple page with a strange issue. Even two senior front-end developers could not find out why. Here is the code, very simple and easy to understand

        <html>
    <head>
    <style type="text/css">
    body
    {
        padding-left:250px;  
    }

    #box1
    {
        width:150px;
        height:150px;
        background-color:#063;
        margin-bottom:10px;
        text-align:center;
        line-height:150px;  
        float:left; 
    }

    #box2
    {
        width:150px;
        height:150px;
        background-color:#00F;
        margin-bottom: 15px;
        text-align:center;
        line-height:150px;
    }
    #box3
    {
        width:150px;
        height:150px;
        background-color:#FC3;
        text-align:center;
        line-height:150px;
    }
    </style>
    </head>

    <body>
    <div id="box1">box1 green</div>
    <div id="box2">box2 blue</div>
    <div id="box3">box3 yellow</div>
    </body>

    </html>

Since #box1 is float:left, so it will be on the top of the page, and the #box2 should be invisible (covered by #box1).

However, when i view it from firefox/chrome, i can see the text of #box2 still visible and the text's position is not right.

I want to know why the text is visible and at the wrong place and how to fix.

I really appreciate your help.

Thank you Luke

Upvotes: 2

Views: 63

Answers (2)

Gibbs
Gibbs

Reputation: 22964

DEMO

Try the above link . Just set position for your box1.

    position:absolute

It works fine.

REASON:

Since you don't use any position it will be considered as static position rather than default.

STATIC POSITIONING: Part of page flow. Scrolls normally. No position change.

ABSOLUTE POSITIONING: It is out of page flow. It is usually moved from original position[0,0].

Upvotes: 2

Chathuranga K
Chathuranga K

Reputation: 226

You can use position absolute, instead of float. float will not work that way. Below code will help

<style type="text/css">
body
{
    padding-left:250px;  
}

#box1
{
    position:absolute;
    z-index:10;
    width:150px;
    height:150px;
    background-color:#063;
    margin-bottom:10px;
    text-align:center;
    line-height:150px;  
}

#box2
{
    position:relative;
    z-index:8;
    width:150px;
    height:150px;
    background-color:#00F;
    margin-bottom: 15px;
    text-align:center;
    line-height:150px;

}
#box3
{
    width:150px;
    height:150px;
    background-color:#FC3;
    text-align:center;
    line-height:150px;
}
</style>

You can use z-index value to determine which div is on top. Remove the background color of box1 and see, then you will see the box 2 is underneath box1

Upvotes: 0

Related Questions