简体   繁体   中英

Padding on a:before pseudo element

I am trying to style some links with lines underneath using the :before pseudo element. The link element has some padding that I cannot change. I have set the before position to absolute to show the line, but as I understand, this means the padding of the link gets counted as part of the :before element width. I have tried using box-sizing: content-box; but the padding space still gets included.

What I trying to achieve is for the line to only go as far as the link text and not into the padding 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;
}

jsfiddle

Thanks

use the css calc as : width: calc(100% - 2em);

here is the fiddle : https://jsfiddle.net/hellooutlook/krgLeq6h/1/

Do it with background and you will have better control:

 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>

You could use the left and right properties (matching the x -padding of your anchor) and drop the 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM