如何使 div 内的链接填满整个 div 空间?

64
我有一个设置了宽度并被包裹在链接中的
。我希望里面的链接填满整个
的空间,以便在我点击
内任何地方(我已经将其样式设置为按钮)时,它都可以转到链接。这是我的尝试,但.link_class不能实现我想要的效果。有什么建议吗?
HTML:
<div class="button_class">
    <a class="link_class" href="http://www.my_link.com>My Link</a>
</div>

CSS:

.button_class {
    width:150px;
    padding:5px 7px;
    color:#fff;
    text-align:center;
    -webkit-border-radius:3px;
    -moz-border-radius:3px;
    border-radius:3px;
}

.link_class {
    width:100%;
    height:100%;
}

1
你可以在你的 .link_class 中使用 display:block,它会起作用。 - The Mechanic
8个回答

86

这应该能解决问题:

默认情况下,a 是一个内联元素,宽度不会影响它们。因此,将其更改为内联块级元素,才能使其具有您指定的宽度。

.link_class {
    display:inline-block;
    width:100%;
    height:100%;
}

Fiddle


这有所帮助,但链接仅延伸到div的填充。 - Nancy Collier
是的,你期望什么?我的意思是它延伸到填充区域吗? - PSL
1
我希望它填满整个div,而不是除去padding后的整个div。 - Nancy Collier
2
你可以尝试在<a>标签中添加负边距。 - Steven
1
这很好,但如果我给我的 div 一个高度,链接就会固定在顶部。如何将其垂直居中对齐?paddng-top 不太合适,因为 div 的高度可能会改变。 - Nikhil VJ
这个在div元素上运作得非常好,但是有一种特殊情况却似乎无法奏效;当链接包含在带有rowspantable列中时(高度为100%未被纳入考虑)。 看起来需要一个固定高度的包装器才能实现这个技巧。 - Ishikawa

7

这里是解决方案

HTML代码:

<div class="button_class">
    <a class="link_class" href="http://www.my_link.com">My Link</a>
</div>

CSS:

.button_class {
    width:150px;
    color:#fff;
    text-align:center;
    -webkit-border-radius:3px;
    -moz-border-radius:3px;
    border-radius:3px;
    background:blue;
}

.link_class {
    display:block;
    color:#ffffff;
    overflow:auto;
    padding:5px 7px;    
}

希望这能帮到你。

我希望这个解决方案能够满足您的需求 - @Nancy Collier - Nitesh
我喜欢这个,但我不明白它为什么能工作。是因为 link_class 中的 padding 填满了 button_class div 吗(假设它确实填满了)?而 overflow:auto 确保了永远不会溢出吗? - codenoob
1
@codenoob - 是 display:block 让它起作用的。 - Nitesh

4

我知道这是一个老问题,但是HTML5有更好的方法来解决这个问题。

今天的答案是:

HTML:

<a class="link_class" href="http://www.my_link.com>
   <div class="button_class">My Link</div>
</a>

CSS保持不变,除了你不再需要使用.link_class。

这会改变原始的HTML。 - rovr138
1
是的,它可以。而且它是这样工作的。https://css-tricks.com/snippets/jquery/make-entire-div-clickable/ - ScottM
2
谢谢!这可能是或可能不是 OP 寻找的,但正是我所需要的。 - Carl Shiles

3

这个方法可行。关键是要明确设置 div 的高度,然后在链接上使用 line-height

.button_class {
    width:150px;
    height:30px;
    color:#fff;
    text-align:center;
    -webkit-border-radius:3px;
    -moz-border-radius:3px;
    border-radius:3px;
}

.link_class {
    display:inline-block;
    width:100%;
    line-height:30px;
}

2
你需要使链接成为块级元素。
.link_class {
    display: block;
}

2
为什么一开始要使用外部 div?将所有代码编写为链接并将其显示为按钮即可简化问题。
.link_class{width:150px;height:30px;color:#fff;text-align:center;display: block;
           -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px;
           /*some other styles*/}

请查看此演示:Fiddle


1
.button_class {
    display:flex;
}

.link_class {
  flex-grow: 1;
  text-align: center;   
}

-2

您可以在a元素中使用bootstrap的class="stretched-link",它会扩展到您的div。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接