skip to Main Content

There is a horizontal menu:

<ul>
  <li>Text</li>
  <li>Text 2</li>
</ul>

When User click over one the li becomes a font-weight bold. Therefore the width of element li is a bit changed. As result I got jumping menu.

How to fix it independent width of text?

4

Answers


  1. you can use css to prevent changes in li width like:

    ul li {
       width: 150px;
    }
    

    this will prevent jumping

    Login or Signup to reply.
  2. When you don’t adjust the width, when the width is changed by other properties(font size, style, etc.), the width will increase or decrecse as needed.

    You can set the width of the element to be fixed and You can use width: max-content.

    Login or Signup to reply.
  3. Instead of directly applying font-weight: bold; to the li elements, you can use a trick to simulate the bold effect without changing the width.

      ul {
        list-style: none;
        padding: 0;
      }
    
      li {
        margin: 10px 0;
        transition: text-shadow 0.3s ease;
      }
    
      li:hover {
        text-shadow: 1px 0 0 #000;
        font-weight: normal; /* Optionally reset font-weight */
      }
    <ul>
      <li>Text</li>
      <li>Text 2</li>
    </ul>
    Login or Signup to reply.
  4. Use :before pseudo-element with font-weight: 700; and content: attr(data-text);:

    ul{
      padding: 0;
      list-style: none;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      row-gap: 8px;
    }
    
    ul li {
      position: relative;
      white-space: nowrap;
    }
    
    ul li:before {
      content: attr(data-text);
      font-weight: 700;
      opacity: 0;
      transition: opacity .4s;
    }
    
    ul li span {
      position: absolute;
      inset: 0;
      transition: opacity .4s;
    }
    
    ul li:hover span {
      opacity: 0;
    }
    
    ul li:hover:before {
      opacity: 1;
    }
    <ul>
      <li data-text="Text">
        <span>Text</span>
      </li>
      <li data-text="Text 2">
        <span>Text 2</span>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search