Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<div> shrinks when float is applied to its sub elements

I am trying to make an element container within the main container of my website. To make the element container in a line, I applied float:left; to them. But when I added float to them,the main container shrinks! I tried applying clear:both to the main container, but nothing changes.

CSS :

#main_container
{
    clear:both;
    margin-top:20px;
    padding:20px 10px 30px 15px;
    background:#ccc;
}
.element_container
{
    float:left;
    width:238px;
    height:300px;
    border:1px solid #000;
}

HTML :

<div id="main_container">

    <div class="element_container"></div>

    <div class="element_container"></div>

    <div class="element_container"></div>

</div>

enter image description here

like image 497
Nitish Avatar asked Jul 16 '12 06:07

Nitish


People also ask

How do you stop DIVS from sliding when floating?

Set height and width to 100% for the bottom div and set overflow auto on the bottom div as well. Now the div will not move up to fill space.

What happens when you float an element?

The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow (in contrast to absolute positioning).

Can you float a div?

Its most common use is to wrap text around images. However, you can use the float property to wrap any inline elements around a defined HTML element, including lists, paragraphs, divs, spans, tables, iframes, and blockquotes.

What are the disadvantages of float in CSS?

Floating everything can make for a great deal of inconsistency; depending on how wide a screen is and how tall certain elements are rendered, you can end up with a hodgepodge of screen jag. For example, widening the screen would cause more elements to fit on the top line, so they would jump up.


1 Answers

Try adding:

overflow: auto;

to #main_container

EDIT: As an alternative float clearing method you can use :after, as explained here.

like image 74
Jonathan Nicol Avatar answered Sep 22 '22 22:09

Jonathan Nicol