Search code examples
htmlcsslayoutflexboxoverflow

How to prevent overflowing of an element in css?


So I am trying to create a logo and a menu icon in the header but for some reason, they are always overflowing the height of the header which I have strictly specified! Why is that ?

And I know I can hide out the overflowing items by using overflow:hidden; property but it is not always a good case.

For example, I tried to create a hamburger icon but I could not because of this overflow issue. The menu lines were working as if the entire element is shown but I had to hide it out so that it could fit into the header.

Here is the code -

    <header>
  <div class="logo">
Elvis
  </div>
  
   <div class="menu">
Hamburger Menu
  </div>
  
</header>

In CSS -

    *{
  padding:0px;
  margin:0px;
}

header{
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 2px solid red;
}

.logo {
  font-size: 33px;
  text-decoration: none;
  padding: 20px 30px;
  background-color: green;
  color: white;
}

.menu {
  height: 100px;
  width: 100px;
  background-color: #bd4439;
}

Here is the codepen link - https://codepen.io/raghav-sharma333/pen/eYeZYGO

Here is the image of the issue - Overflowing content

So I just want to know :

  1. Why is it happening?

&

  1. How can it be prevented?

Solution

  • Basically you are forcing your elements to be higher than the header itself by giving them static heights (height 100px on the menu and padding-top/bottom 30px on the logo)

    I updated your pen: https://codepen.io/penmasterx/pen/wvPGaGz

    Using height 100%, so the elements adapt to the header.

    Let me know if this solves your problem. If not, let me know in more detail what you're trying to accomplish.

    What I added to the pen:

    .logo {
      height: 100%;
      display: flex;
      align-items: center;
      /* removed padding top/bottom */
    }
    
    .menu {
      height: 100%;
    }