skip to Main Content

I have a list of menu items. The goal is for the font to become bold when I select one of the items. However, when I do this, the other items shift slightly. I tried to add width, but then I have different spacing between items. How can I make these items remain static when one of them is selected?

enter image description here

return (
    <div>
      <div className="flex flex-wrap items-center gap-5 justify-between max-w-7xl m-auto text-xl">
        {genres.map((genre, index) => {
          return (
            <button
              key={index}
              className={`${
                selectedGenre === index ? 'font-bold' : 'font-normal'
              }`}
              onClick={() => onSelect(index)}
            >
              {genre.toUpperCase()}
            </button>
          )
        })}
      </div>
    </div>
  )

2

Answers


  1. By adding w-full class to all buttons, you’re ensuring that they all have the same width regardless of their content or whether they are selected.

    return (
      <div>
        <div className="flex flex-wrap items-center justify-between max-w-7xl m-auto text-xl">
          {genres.map((genre, index) => {
            return (
              <button
                key={index}
                className={`${
                  selectedGenre === index ? 'font-bold' : 'font-normal'
                } w-full`} // Add w-full to ensure all buttons have the same width
                onClick={() => onSelect(index)}
              >
                {genre.toUpperCase()}
              </button>
            )
          })}
        </div>
      </div>
    )
    
    Login or Signup to reply.
  2. Becasue button is an inline-block element and doesn’t have an explicit width, so it shrink-wraps the content.

    To solve it, give the button element a fixed width and set style of it to block. Or use a monospace font.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search