Search code examples
csscss-float

float: none; inside media query resets styling


I have the following code:

.headerButton {
  position: relative;
  float: right;
  width: fit-content;
  height: fit-content;
  line-height: 0;
  margin: 0px 10px 0px 0px;
  padding: 0px 20px 0px 20px;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
  border-radius: 50px;
  font-size: 20px;
  color: rgb(15, 15, 15);
  transition-duration: 0.3s;
}

.headerButton:hover {
  cursor: pointer;
  background-color: rgb(230, 230, 230);
  color: rgb(15, 15, 15);
}

@media only screen and (max-width: 1000px) {
  .headerButton {
    float: none;
    left: 50%;
    -webkit-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    transform: translateX(-50%);
  }
}
<div class="headerButton">
  <p>Login</p>
</div>
<div class="headerButton">
  <p>Sign up</p>
</div>
<div class="headerButton">
  <p>Explore</p>
</div>
<div class="headerButton">
  <p>About</p>
</div>

For some reason when I rescale the window and media query becomes active, many of the properties specified in .headerbutton {} stop working (for some reason the background and border radius are working on hover). I have confirmed that it's the float property's fault by removing it.

I have tried using clear: both; , but it messes up the width and and positioning of the buttons.


Solution

  • Float is not considered a best practice anymore, I suggest Flexbox instead. And concerning the hover effect, it's not showing because the spaces between elements are too tight, that explains why the pointer changes but the background color doesn't. Try this: HTML

    <ul class="menu">
    <li class="headerButton">
        <p>Login</p>
    </li>
      <li class="headerButton">
        <p>Sign up</p>
      </li>
      <li class="headerButton">
        <p>Explore</p>
      </li>
      <li class="headerButton">
        <p>About</p>
      </li>
    </ul>
    

    CSS

    .menu{
            list-style: none;
            display: flex;
            justify-content: space-between;
        }
    .headerButton {
    width: fit-content;
    height: fit-content;
    margin: 0px 10px 0px 0px;
    padding: 0px 20px 0px 20px;  top: 50%;border-radius: 50px;  
    font-size: 20px;  color: rgb(15, 15, 15);  
    transition-duration: 0.3s;
    }
    .headerButton:hover {cursor: pointer;  
    background-color: rgb(230, 230, 230);  
    color: rgb(15, 15, 15);
    }
    @media only screen and (max-width: 1000px) {
    .menu{
    display: block;
    }
    .headerButton{
    text-align: center;
    margin: 0 auto;
    padding: 1rem;
    }
    }