2

I'm trying to create few divisions and apply different background for each division but my code is not working as expected.

HTML

<div class="main">
    <div id="div1">Im in div-1</div>
    <div id="div2"></div>
    <div id="div3"></div>
</div>

CSS

.main{
    background-color:red;
}
#div1 {
    height:200px;
    width:100px;
    float:left
}
#div2 {
    height:200px;
    width:500px;
    float:left
}

When I set the background color for each id, it's working as expected but when I set for the class it's not working.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
user1050619
  • 19,822
  • 85
  • 237
  • 413

3 Answers3

4

It works, you don't see it because your floating divs are not wrapped by the parent.

Add overflow:hidden to the parent div

Fiddle

Phil-R
  • 2,193
  • 18
  • 21
2

Here U can achieve this by using floated divisions (divs) clearing without using structural markup. It is very effective in resolving layout issues and browser inconsistencies without the need to mix structure with presentation.

Read this

http://perishablepress.com/lessons-learned-concerning-the-clearfix-css-hack/

http://css-tricks.com/snippets/css/clear-fix/

Try this -

<div class="main clearfix">
    <div id="div1">Im in div-1</div>
    <div id="div2"></div>
    <div id="div3"></div>
</div>

In your CSS - Add this

.clearfix:after {
     visibility: hidden;
     display: block;
     font-size: 0;
     content: " ";
     clear: both;
     height: 0;
}

DEMO

TNK
  • 4,263
  • 15
  • 58
  • 81
0

You need to add overflow:hidden; to the parent div, so it should look like this: .main{ overflow: hidden; background-color:red; }