如何创建一个不添加边距的边框?

时间:2022-12-08 07:20:24

I'm new to HTML/CSS, and I'm learning Bootstrap.

我是HTML / CSS的新手,我正在学习Bootstrap。

I'm coding a Bootstrap navbar and I have a small difficulty, here's a fiddle of the work I have done.

我正在编写一个Bootstrap导航栏,我有一个小难度,这里是我所做的工作的小提琴。

In the HTML code there is the normal markup that goes into building a TWBS navbar, and I have added code to change the color of the active tab:

在HTML代码中有构建TWBS导航栏的常规标记,我添加了代码来更改活动选项卡的颜色:

.navbar-nav a.active {
    -webkit-transition: .2s;
    -o-transition: .2s;
    transition: .2s;
    border-top: 2px solid #212121;
}

Problem: The text wrapped within the<a> tag is now slightly pushed down and I am noticing that the border-top CSS property functions more like a margin-top property.

问题:标签中包含的文本现在略微下推,我注意到border-top CSS属性更像是margin-top属性。

How do I avoid this and create a border that doesn't add the margin?

如何避免这种情况并创建一个不添加边距的边框?

3 个解决方案

#1


4  

You can style :before pseudo element of the active a and position it relatively to the parent element:

您可以设置样式:在活动a的伪元素之前,并将其相对于父元素定位:

.navbar-nav a.active:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 2px;
}

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

#2


4  

You could use an inset box shadow:

您可以使用插入框阴影:

box-shadow: inset 0px 3px 0px 0px #212121;

This has the benefit of not changing the elements size OR requiring a pseudo element but sadly isn't supported in <=IE8 ;(

这样做的好处是不会改变元素大小或需要伪元素,但遗憾的是<= IE8不支持;(

See: http://jsfiddle.net/djuj5jte/3/

#3


1  

You can add

你可以加

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

so that the border will be part of the element width.

这样边框将成为元素宽度的一部分。

Useful link: https://css-tricks.com/box-sizing/

有用的链接:https://css-tricks.com/box-sizing/

#1


4  

You can style :before pseudo element of the active a and position it relatively to the parent element:

您可以设置样式:在活动a的伪元素之前,并将其相对于父元素定位:

.navbar-nav a.active:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 2px;
}

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

#2


4  

You could use an inset box shadow:

您可以使用插入框阴影:

box-shadow: inset 0px 3px 0px 0px #212121;

This has the benefit of not changing the elements size OR requiring a pseudo element but sadly isn't supported in <=IE8 ;(

这样做的好处是不会改变元素大小或需要伪元素,但遗憾的是<= IE8不支持;(

See: http://jsfiddle.net/djuj5jte/3/

#3


1  

You can add

你可以加

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

so that the border will be part of the element width.

这样边框将成为元素宽度的一部分。

Useful link: https://css-tricks.com/box-sizing/

有用的链接:https://css-tricks.com/box-sizing/