-3

Here's my source code, what is wrong with it?

CSS:

 .no1.right {text-align: right;float : right}
 .no1.left {text-align : left;float : left}
 .no1 {background-color: blue}

HTML:

<div class="no1">
    <div class="right">a</div>
    <div class="left">b</div>
</div>

Why the background-color not working ?

pavel
  • 26,538
  • 10
  • 45
  • 61
  • 2
    Because you have float elements inside. They do not add to the height. Read up about float and clearfix. Also you should make your question more readable then this.Not put give us code and say fix it. – Ruddy Jan 05 '15 at 08:40
  • 5
    possible duplicate of [How do you keep parents of floated elements from collapsing?](http://stackoverflow.com/questions/218760/how-do-you-keep-parents-of-floated-elements-from-collapsing) – Abhitalks Jan 05 '15 at 08:40
  • 1
    I love the fact the linked duplicate itself has been closed as a duplicate... – SW4 Jan 05 '15 at 08:44

2 Answers2

5

You have to clear after floating elements, the fastest way is

.no1 {overflow: hidden}

Floating elements has zero-height, parent element has the same (zero) height. Blue background is applied, but only in the element (zero) height.

The second way is to add element with clear:

<style>
    .cleaner {clear: both}
</style>

<div class="no1">
    <div class="right">a</div>
    <div class="left">b</div>
    <div class=cleaner></div>
</div>
pavel
  • 26,538
  • 10
  • 45
  • 61
  • @Ruddy: in this case it doesn't matter, using `overflow` don't need changes in HTML. – pavel Jan 05 '15 at 08:42
  • Using a pseudo element would also require no changes to the HTML. – Ruddy Jan 05 '15 at 08:43
  • Changing overflow is a valid approach if there isnt any subsequent content within the parent, though semantically you're better off using `overflow:auto` – SW4 Jan 05 '15 at 08:44
  • Floating elements doesn't have a zero height. The reason that the parent element height is zero is that the height of the floating elements doesn't affect the height of the parent element. – Guffa Jan 05 '15 at 08:46
1

Add to your wrapper div float: left; and add ; append blue.

.no1 {
  float: left;
  background-color: blue;
}
Mardzis
  • 760
  • 1
  • 8
  • 21