Sachin
Sachin

Reputation: 3782

Parent div height becomes smaller than child div height when it is floated right

I have the following html code when I have the attribute float right then the height of the parent div becomes smaller than the child's div

 <div id="notificationBar"> 
    <div style="float:right;">
        {% if user.is_authenticated %}
            Hello {{ user }}
            <a href ="/accounts/logout/" style="margin-left:10px;"> Logout </a>
        {% else %}
            Hello Guest
            <a href ="/accounts/login/" style="margin-left:10px;"> Login </a>
        {% endif %}
    </div>
</div>

enter image description here

However when I remove th float right attribute as given below then the parent div accommodates the child div as it should normally behave.

<div id="notificationBar">  
    <div>
        {% if user.is_authenticated %}
            Hello {{ user }}
            <a href ="/accounts/logout/" style="margin-left:10px;"> Logout </a>
        {% else %}
            Hello Guest
            <a href ="/accounts/login/" style="margin-left:10px;"> Login </a>
        {% endif %}
    </div>
</div>

enter image description here

Can anybody explain why is this happening. One solution is to set a height of the parent div, but then that is not a flexible solution. I want the height of the parent div to be changed according to the height of the child div.

Upvotes: 1

Views: 3874

Answers (3)

ngsiolei
ngsiolei

Reputation: 614

How about clear the floating as follows

<div id="notificationBar">
    <div style="float:right;">
        {% if user.is_authenticated %}
            Hello {{ user }}
            <a href ="/accounts/logout/" style="margin-left:10px;"> Logout </a>
        {% else %}
            Hello Guest
            <a href ="/accounts/login/" style="margin-left:10px;"> Login </a>
        {% endif %}
    </div>
    <div style="clear: both; height: 0;"></div>
</div>`

Upvotes: 4

ijse
ijse

Reputation: 3035

add css:

#notificationBar { overflow:auto; }

Upvotes: 2

Scott
Scott

Reputation: 21882

Why have a div at all? Why not simply set the text to align right? Float's have no inherent block height. They won't ever keep a partent div as a block if you float internal elements. You could use float: right; display: inline-block; or....

What I would do....

<div id="notificationBar" style="text-align: right;"> 
    {% if user.is_authenticated %}
        Hello {{ user }}
        <a href ="/accounts/logout/" style="margin-left:10px;"> Logout </a>
    {% else %}
        Hello Guest
        <a href ="/accounts/login/" style="margin-left:10px;"> Login </a>
    {% endif %}
</div>

or use a paragraph rather than a div.

Of course, there maybe other factors you aren't sharing.

Upvotes: 2

Related Questions