Search code examples
htmlcsswebkit

CSS block-level vs inline container issue


Here is the demo http://jsfiddle.net/aTBWh/

the container is id(div) meaning it inherits a display:block value from the browser, the two div's inside this container are classes. they both have 200px and 300px while the main container has 600px width, so I thought when I floated one of the classes to the right, it should only consume 300px from the whole container meaning the two div's should fit inside the container without one appearing above the other. there is no clear:both attribute.

if the container is an id, with 600px, then the classes nested inside it (specially when one is floated to right, they should fill the container.)

in a nutshell why is the green div class out of the container when it can clearly fit there, and it is floated to the right? I don't understand this problem.

codes: css

#content_canvas_container{
    background:#CCC; 
    min-height:200px; 
    border:1px solid red;
    width:600px;
}
.red{
    width:200px; 
    background:red; 
    height:140px; 
}

.green{
    width:300px; 
    background:green; 
    height:140px; 
    float:right;
}

/*PROPERTIES*/
.w90{width:98%} 
.m_auto{margin:auto; border:1px solid black}

html

<section id='content_canvas_container'>
 <div class='w90 m_auto'>
   <div class='red'> red </div>
   <div class='green'> green </div>
 </div>
</section>

Solution

  • What you are seeing is expected behavior.

    The reason this is occurring is because the red div element is a block level element by default. Thus, in its current state, it will always appear on a new line regardless of whether it has a defined width or has floating sibling elements.

    By floating or absolutely positioning an element, you are essentially removing it from the flow of the document, rendering display:block ineffective. Therefore you can solve this by either floating the red div element, or adding display:inline-block to it. (example)

    jsFiddle example

    .red {
        width: 200px;
        background: red;
        height: 140px;
        float: left;
    }