我可以用 CSS 将边框居中吗?

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

Can I center a border with CSS?

cssborder

提问by Rob

I'm trying to center the dotted line horizontally with CSS. At the moment, it appears at the bottom. Is there a way I can offset it with -5px or something?

我试图用 CSS 将虚线水平居中。目前,它出现在底部。有没有办法用 -5px 或其他东西来抵消它?

HTML

HTML

<div class="divider"></div>

CSS

CSS

.divider {
    background: aqua url("styles/images/divider-stars.png") no-repeat center 0;
    height:30px;
    padding-bottom: 10px;
    width: 100%;
    margin: 20px auto;
    float: left;
    border-bottom: 2px dotted #b38b0d;
    }

回答by Sotiris

no. But you can create another element that have the borderand move it within the .divider

不。但是您可以创建另一个具有 的元素border并将其移动到.divider

html

html

<div class="divider">
    <div class="inner"></div>
</div>

css

css

.inner {
 margin-top:19px;
 border-bottom: 2px dotted #b38b0d;   
}

Demo:http://jsfiddle.net/5xMG7/

演示:http : //jsfiddle.net/5xMG7/

回答by gyo

You could also use :beforeor :afterpseudo-selectors, to get rid of the inner element.

您还可以使用:before:after伪选择器来摆脱内部元素。

<div class="divider"></div>
.divider {
    background: aqua url("styles/images/divider-stars.png") no-repeat center 0;
    height: 30px;
    padding-bottom: 10px;
    width: 100%;
    margin: 20px auto;
    float: left;
}

.divider:after {
    content: '';
    display: block;
    margin-top: 19px;
    border-bottom: 2px dotted #b38b0d;
}

http://jsfiddle.net/5xMG7/540/

http://jsfiddle.net/5xMG7/540/

回答by David Aleu

If you mean center it vertically, one way you can do it is like this:

如果你的意思是垂直居中,你可以这样做的一种方法是这样的:

<div class="divider"><span class="line"></span></div>

.divider {
    background: aqua url("styles/images/divider-stars.png") no-repeat center 0;
    height:30px;
    padding-bottom: 10px;
    width: 100%;
    margin: 20px auto;
    float: left;
    }
.line
{
   border-bottom: 2px dotted #b38b0d;
   margin-top:15px;
    display:block;
}