Home > front end >  CSS element not floating when float property specified
CSS element not floating when float property specified

Time:03-30

I am trying to float a navbar element so it can be taken outside of its float and displayed on top of the second element which is a div. unfortunately, i figured that the navbar didn't float when the css display property of the div below the navbar is set to flex. is there anyway to get around this problem while keeping the div as a flex? without wrapping the both element inside a div. the goal is to get the same background for both element navbar and div without wrapping them inside one div.

<ul >
  <li><a href="#" >Home</a></li>
  <li><a href="#" >Act Now!</a></li>
  <li><a href="#" >FAQ</a></li>
  <li><a href="#" >Contact Us</a></li>
</ul>
<div >
</div>


.nav{ 
  display:flex;
  justify-content:center;
  width:100%;
  float:left;
}

.nav li {
  background:#000;
  list-style: none;
  height: 60px;
  line-height: 60px;
  padding: 0 40px;
  margin:0px 20px;
  box-shadow: 0px 4px 16px rgba(121, 121, 121, 0.25);
  border-radius: 60px;
}

.nav li:hover {
  background: red;
  transition: background .3s;
}

.nav-link {
  color: #fff;
  text-decoration: none;
}

.hero{
  background:#999;
  height:100px;
  display:flex;
  width:100%;
}

https://codepen.io/nidhalmejai/pen/LYejGbY the problem is the navbar is not floating if the div below it has a display flex.

CodePudding user response:

give your * element

position:relitive;

add these styles to .hero

 position:absolute;
  z-index:-1;

https://codepen.io/abdurrahmanseyidoglu/pen/abEyNBm

CodePudding user response:

While your question is quite unclear, what I understand is that you want the background on "hero" to be the background for your "nav".

I give you 2 solutions -

  1. Remove "hero". Just use "nav" and add the background styles to it (along with appropriate padding).

    .nav { 
        display:flex;
        justify-content:center;
        width:100%;
        background:#999;
        padding: 20px 0; // padding is just to make this look better
    }
    // Instead of padding, you could set a height to this flex and force it's children
    // to be vertically aligned to the center using vertical-align: middle on .nav AND
    // margin: 20px; on .nav li instead of the current margin: 0 20px;
    
  2. Keep the "hero" element as it is. Use positioning on "nav" to achieve this effect (you mentioned not wanting to wrap the tags in one common div - that means position absolute, would not work for you). But position: fixed OR position: sticky might

    .nav { 
        display:flex;
        justify-content:center;
        width:100%;
        position: fixed;
        padding: 20px 0; // padding is just to make this look better
    }
    
  • Related