Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS block-level vs inline container issue

Tags:

html

css

webkit

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>
like image 980
samayo Avatar asked May 10 '26 05:05

samayo


2 Answers

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;
}
like image 139
Josh Crozier Avatar answered May 12 '26 02:05

Josh Crozier


That happens because when you set a float to a box, it moves to the left or the right of the container (according with other complex rules, of course), but it's vertical offset from the top of the container can't be smaller than it would be if it wasn't floated.

like image 29
Carlo Cannas Avatar answered May 12 '26 00:05

Carlo Cannas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!