0

I want to apply selected li a border, but seems hovering have a problem of flickering. Tried box-sizing still can't solve it.

li {
  background: red;
}

li:hover {
  border: 1px solid blue;
  box-sizing: border-box;
}

Am I missing something?

https://jsfiddle.net/wf0r2c5q/1/

Sharon Chai
  • 507
  • 1
  • 6
  • 20
  • Dupe of https://stackoverflow.com/questions/8625812/css-hover-border-makes-inline-elements-adjust-slightly and https://stackoverflow.com/questions/9612758/add-a-css-border-on-hover-without-moving-the-element and https://stackoverflow.com/questions/5578606/css-link-element-jumps-on-hover and https://stackoverflow.com/questions/556153/inline-elements-shifting-when-made-bold-on-hover – j08691 Feb 14 '18 at 03:47

4 Answers4

1

Add a border: 1px solid transparent to the li state.

li {
  background: red;
  border: 1px solid transparent;
}

It is flickering because a border changes the layout of the element.

Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
1

Initially set the border-color to transparent and on :hover state set border-color to your choice

Stack Snippet

li {
  background: red;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border-top: 1px solid transparent;
  border-bottom: 1px solid transparent;
}

li:hover {
  border-color: blue;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

...or another solution is use box-shadow inset instead of border

li {
  background: red;
}

li:hover {
  box-shadow: 0px 1px 0 0px blue inset, 0px -1px 0 0px blue inset;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
0

Just add a border: 1px solid red or 1px solid transparent on the li tag. The flickering you see is because you pass to 0px border to a 1px border

0

I assume by 'flickering' you're talking about the slight change in position of the bullet point when you hover over the inner <li>. This is due to the fact that when you add your border, it shifts the bullet points down the page.

You can compensate for this by adding margin: -1px auto to your :hover state:

li {
  background: red;
}

li:hover {
  border: 1px solid blue;
  margin: -1px auto;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

Hope this helps!

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71