html - 防止左侧填充将元素推向右侧

标签 html css

我有一些预览文本,后跟一个带有翻转的链接,我试图确保链接的文本与预览文本的文本对齐。这在没有填充的情况下工作正常:

enter image description here

但是,向 anchor 元素添加内边距会导致整个元素向右移动左内边距的量:

enter image description here

我怎样才能使填充以某种方式应用于元素父容器的外部?如果这不可能,我如何简单地确保预览文本和链接的文本都是左对齐的?

这是相关的 HTML:

<div id="hero-about-container">

<div id="hero-about-text-container">    
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
</div>

<a id="hero-about-link" href="localhost/wordpress/about">Read more about the history of the centre <span id="icon">&#187;</span></a>

</div>

...以及相应的 CSS:

#hero-about-text-container {
  line-height: 40px;
  width: 50%;
  margin-top:30px;
}

#hero-about-link {
  padding: 3px 5px 3px 5px;
  vertical-align: middle;
  -webkit-transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  overflow: hidden;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-property: color, background-color;
  transition-property: color, background-color;

}

#hero-about-link:hover, 
#hero-about-link:focus, 
#hero-about-link:active {
  background-color: #FFF;
  color: #000;
}

感觉这应该是一个足够普遍的问题,因此有一个简单的解决方案,但我不知道那是什么。我知道 box-sizing:border-box 设置在祖先元素的某处,所以这是我的第一个想法,但是在 anchor 上设置 box-sizing:content-box元素似乎没有什么不同。

最佳答案

与 Oliver 的回答类似,您也可以通过填充代替左右边框来实现它。

.wrapper {
  background: whitesmoke;
  padding: 20px;
}

a{
  text-decoration: none;
}

a:hover, a.highlighted {
  background: blue;
  padding: 0 5px;
  margin-left: -5px;
  color: white;
}
<div class="wrapper">
  <p>Some text here</p>
  <a href="#">Anchor text here</a><br>
  <a href="#" class="highlighted">Anchor text here</a>
</div>

关于html - 防止左侧填充将元素推向右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589955/

相关文章:

css - 自定义列表样式不适用于自动换行,不知道为什么

html - 在按钮 CSS 上居中文本

html - 适用于iPhone/iPad的HTML5视频。如何检测连接速度?

javascript - 在 DIV 中重复图像后跟另一个图像

html - IFRAME 在 IE8 中不会显示 100% 高度,但在 IE11 和 Firefox 中正常

html - CSS 购物车下拉菜单

html - 如何在 flex block 中定位 block ?

css - 如何让通知框 float 在中间

jquery - 使用 jQuery 获取属性名称值

jquery - 无法使用 jQuery 在 HTML5 Canvas 上绘制