Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a CSS border on hover without moving the element [duplicate]

Tags:

css

People also ask

How do I apply a border to the element on a mouse hover without affecting the layout in CSS?

Answer: Use the negative CSS margin.

How do you make a border appear on hover?

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc. That was the best solution for me because, in my case, I set a 1px border to the orignal element and want to get, on hover, a thicker border (3px). Using margin: -2px; indeed works.

How do you avoid double border in CSS?

Add a border-left and border-top to the parent. Add border-right and border-bottom to each of the children.


You can make the border transparent. In this way it exists, but is invisible, so it doesn't push anything around:

.jobs .item {
   background: #eee;
   border: 1px solid transparent;
}

.jobs .item:hover {
   background: #e1e1e1;
   border: 1px solid #d0d0d0;
}
<div class="jobs">
  <div class="item">Item</div>
</div>

For elements that already have a border, and you don't want them to move, you can use negative margins:

.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
   background: #e1e1e1;
    border: 3px solid #d0d0d0;
    margin: -2px;
}
<div class="jobs">
  <div class="item">Item</div>
</div>

Another possible trick for adding width to an existing border is to add a box-shadow with the spread attribute of the desired pixel width.

.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
    background: #e1e1e1;
    box-shadow: 0 0 0 2px #d0d0d0;
}
<div class="jobs">
  <div class="item">Item</div>
</div>

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.


Try this it might solve your problem.

Css:

.item{padding-top:1px;}

.jobs .item:hover {
    background: #e1e1e1;
    border-top: 1px solid #d0d0d0;
    padding-top:0;
}

HTML:

<div class="jobs">
    <div class="item">
        content goes here
    </div>
</div>

See fiddle for output: http://jsfiddle.net/dLDNA/


Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.