在 a:before 伪元素上填充
Padding on a:before pseudo element
我正在尝试使用 :before 伪元素为一些 link 设置样式,并在下方添加线条。 link 元素有一些我无法更改的填充。我已将前位置设置为绝对以显示该行,但据我了解,这意味着 link 的填充被计为 :before 元素宽度的一部分。我试过使用 box-sizing: content-box;
但填充 space 仍然包含在内。
我想要实现的是让该行只到达 link 文本,而不进入填充 space.
HTML:
<div>
<a href="">heya</a>
<a href="">what's up?</a>
</div>
CSS:
a{
text-decoration: none;
color: black;
position: relative;
padding: 1em;
}
a::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
background-color: #000;
}
谢谢
使用 css calc
如:width: calc(100% - 2em);
这里是 fiddle : https://jsfiddle.net/hellooutlook/krgLeq6h/1/
用背景做,你会更好地控制:
a {
text-decoration: none;
color: black;
padding: 1em;
background:
linear-gradient(#000,#000)
bottom -0.5em center /* position */
/100% 2px /*width height */
no-repeat;
background-origin:content-box; /* this will consider only the content and not the padding */
}
<div>
<a href="">heya</a>
<a href="">what's up?</a>
</div>
您可以使用 left
和 right
属性(匹配锚点的 x-padding)并删除 width
:
a {
text-decoration: none;
color: black;
position: relative;
padding: 1em;
}
a::before {
content: "";
position: absolute;
height: 2px;
bottom: 0;
background-color: #000;
left: 1rem;
right: 1rem;
}
<div>
<a href="">heya</a>
<a href="">what's up?</a>
</div>
我正在尝试使用 :before 伪元素为一些 link 设置样式,并在下方添加线条。 link 元素有一些我无法更改的填充。我已将前位置设置为绝对以显示该行,但据我了解,这意味着 link 的填充被计为 :before 元素宽度的一部分。我试过使用 box-sizing: content-box;
但填充 space 仍然包含在内。
我想要实现的是让该行只到达 link 文本,而不进入填充 space.
HTML:
<div>
<a href="">heya</a>
<a href="">what's up?</a>
</div>
CSS:
a{
text-decoration: none;
color: black;
position: relative;
padding: 1em;
}
a::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
background-color: #000;
}
谢谢
使用 css calc
如:width: calc(100% - 2em);
这里是 fiddle : https://jsfiddle.net/hellooutlook/krgLeq6h/1/
用背景做,你会更好地控制:
a {
text-decoration: none;
color: black;
padding: 1em;
background:
linear-gradient(#000,#000)
bottom -0.5em center /* position */
/100% 2px /*width height */
no-repeat;
background-origin:content-box; /* this will consider only the content and not the padding */
}
<div>
<a href="">heya</a>
<a href="">what's up?</a>
</div>
您可以使用 left
和 right
属性(匹配锚点的 x-padding)并删除 width
:
a {
text-decoration: none;
color: black;
position: relative;
padding: 1em;
}
a::before {
content: "";
position: absolute;
height: 2px;
bottom: 0;
background-color: #000;
left: 1rem;
right: 1rem;
}
<div>
<a href="">heya</a>
<a href="">what's up?</a>
</div>