在不移动元素的情况下在悬停时添加 CSS 边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9612758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:12:23  来源:igfitidea点击:

Add a CSS border on hover without moving the element

css

提问by David542

I have a row that I am applying a background highlight to on hover.

我有一行在悬停时应用背景突出显示。

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

However, as the border adds 1px additionalto the element, it makes it 'move'. How would I compensate for the above movement here (without using a background image)?

然而,随着边境增加了1px的额外的元素,它使得“移动”。我将如何在这里补偿上述运动(不使用背景图像)?

回答by methodofaction

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-top: 1px solid transparent;
}

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

If your elements have a specified heightand/or width, you can also use box-sizing:border-box;, as this box model includes padding and border widths into the computed size, example:

如果您的元素具有指定的height和/或width,您也可以使用box-sizing:border-box;,因为此框模型将填充和边框宽度包含在计算大小中,例如:

.jobs .item {
    background: #eee;
    height: 40px;
    box-sizing: border-box;
}

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

回答by Dips

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

addmargin:-1px;减少1px到每一边。或者如果你只需要一边你可以做margin-left:-1px等。

回答by w3uiguru

Try this it might solve your problem.

试试这个它可能会解决你的问题。

Css:

css:

.item{padding-top:1px;}

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

HTML:

HTML:

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

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

见小提琴输出:http: //jsfiddle.net/dLDNA/

回答by danapaige

Add a borderto the regular item, the same coloras the background, so that it cannot be seen. That way the item has a border: 1pxwhether it is being hovered or not.

a添加border到正规的项目,相同colorbackground,所以它不能被看到。这样,项目就有了border: 1px它是否被悬停的信息。