0

the code contains html code and css code. Here In html I have an ancestor div element with class name navigation and the child I have an unordered list. When I do not set the property to float:right or left it takes the background color of ancestor. however when I set the property of child element to float:right or left the background color is not displayed.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: yellow;
}

.container {}

.navigation {
  background-color: red;
}

ul {
  /* here I am not setting the float property and it is taking the ancestor
   background color */
}

/* CSS changes I made */ 
ul {
  /* here I am setting float property to right */ 
  float: right; 
}
<body>
  <div class="container">
    <div class="logo">
      <img src="https://dummyimage.com/300x100/000/fff">
    </div>
    <button type="button" class="nav-toggler">
                    <span></span>
                </button>
    <nav class="navigation">
      <ul>
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Gallery</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact Us</a></li>
      </ul>
    </nav>
  </div>
</body>

the navigation color in the background gets hidden. Can you please help me why its not displaying the background color red when I change the ul property to float:right

Mushroomator
  • 6,516
  • 1
  • 10
  • 27
  • 2
    I have made your code syntactically correct. You need to use `;` to declare a property and `//` cannot be used to create a line comment in `CSS`. Use `/* some comment */` instead. – Mushroomator May 05 '22 at 14:32
  • Because `float: right` essentially removes the `ul` from the layout of the `nav` this causes the `nav` to collapse to zero height. – phuzi May 05 '22 at 14:32

1 Answers1

0

This is because you did not clear your float

Whenever your job is done you need to clear float effect and if you don't the raw will left open and browser can't calculate the height of your element so your element's height will be 0 and therefore you can't see your background

    <nav class="navigation">
    <ul>
       <li class="active"><a href="#">Home</a></li>
       <li><a href="#">Services</a></li>
       <li><a href="#">Gallery</a></li>
       <li><a href="#">About</a></li>
       <li><a href="#">Contact Us</a></li>
     </ul>
     <div class="clear-fix" ></div>
   </nav>

   .clear-fix{
        clear: both;
   } 
Mahdiar Mransouri
  • 652
  • 1
  • 4
  • 11
  • thank you my problem got solved with your explanation. I used clear fix like this gave the class name clearfix to my wrapper class and then clearfix::after{ content: "", clear:both, display; block} this way I solved this issue – Rahul Singh Jun 11 '22 at 15:03