CSS 如何在不占用html中的任何额外空间的情况下将边框呈现给div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8971004/
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 02:44:19  来源:igfitidea点击:

How to render a border to div without occupying any extra space in html?

css

提问by BalaKrishnan?

I want to draw a border for div without occupying any extra space ?, it mean the border must be inside the div.

我想在不占用任何额外空间的情况下为 div 绘制边框?,这意味着边框必须在 div 内。

回答by Rufus

You have 3 choices:

你有3个选择:

  1. Inner and outer boxes(as @xpapad stated).
  2. Using outline, e.g., outline:1px #000 solid;. Read more.
  3. Using box-sizing, which is a css3 property. E.g., box-sizing:border-box;. Read more.
  1. 内盒和外盒(如@xpapad 所述)。
  2. 使用outline,例如,outline:1px #000 solid;阅读更多
  3. 使用box-sizing,这是一个 css3 属性。例如,box-sizing:border-box;阅读更多

回答by meo

you can compensate it with negative margin, or simply use outline.

你可以用负边距来补偿它,或者简单地使用轮廓。

div { border: 10px solid red; margin: -10px};

or

或者

div { outline: 10px solid red; }

alternatively you could use css3 boxshadow to fake a border...

或者,您可以使用 css3 boxshadow 来伪造边框...

example: http://jsfiddle.net/meo/K23s7/

示例:http: //jsfiddle.net/meo/K23s7/

回答by Richard Rutter

Try using a negative margin equivalent to your border, eg.

尝试使用与您的边框等效的负边距,例如。

border-right:1px;
margin-right:-1px;

回答by FelDev

For my use case, the box-shadow property was the right choice.

对于我的用例, box-shadow 属性是正确的选择。

More precisely, box-shadow with 0 blur and a bit of spread.

更准确地说,是带有 0 模糊和一点点散布的 box-shadow。

The "border" it creates is not inside the div, but it doesn't occupy extra HTML space.

它创建的“边框”不在 div 内,但不会占用额外的 HTML 空间。

button {
    background: white;
    font-size:2rem;
    padding:1rem 2rem;
    color: #4f93df;
    border-radius: 2rem;
    margin:1rem;
}

.withABorder{
  box-shadow: 0px 0px 0px 4px #4f93df;
}
<div>
  <button>Hello</button>
  <button class="withABorder">World</button>
  <br>
  <button>Hello Again</button>
</div>

回答by xpapad

Include an inner div inside your current div, using the required border.

使用所需的边框在当前 div 中包含一个内部 div。