christiannc
christiannc

Reputation: 23

How can I prevent other text from shifting on hover with CSS?

I have a category selector in my React app, and the category labels are displayed with flexbox so that they can be spaced evenly and horizontally. I've applied some styling changes to the hovered text to make the font weight heavier, but doing so has caused the labels surrounding the hovered one to shift. Is there a way I can fix this so that hovering doesnt cause anything to move, but instead just change the font weight?

Here's my CSS:

.skills-category-selector {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-top: 12px;
}

.category-label {
    cursor: pointer;
    font-size: 20px;
    font-weight: 500;
}

.category-label:hover {
    font-weight: 800;
    text-decoration: underline;
}

Upvotes: 1

Views: 1652

Answers (2)

Edgar MC
Edgar MC

Reputation: 11

This solution can help you, you need to use pseudo-elements https://css-tricks.com/bold-on-hover-without-the-layout-shift/ or just assign a specific width on every .category-label

.skills-category-selector {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 12px;
}

.category-label{
  width: 20%;
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
}

.category-label:hover {
  font-weight: 800;
  text-decoration: underline;
}
   <div class="skills-category-selector">
     <span class="category-label">Category 1</span>
     <span class="category-label">Category 2</span>
     <span class="category-label">Category 3</span>
     <span class="category-label">Category 3</span>
   </div>

Upvotes: 0

Nick Vu
Nick Vu

Reputation: 15520

You can use text-shadow to increase text boldness instead

.skills-category-selector {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 12px;
}

.category-label {
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
}

.category-label:hover {
  text-shadow: 1px 0 0 black;
  text-decoration: underline;
}
<div class="skills-category-selector">
  <span class="category-label">Category 1</span>
  <span class="category-label">Category 2</span>
  <span class="category-label">Category 3</span>
</div>

Upvotes: 2

Related Questions