我从这个帖子中学到,制作按钮始终使用<a>
标签或<button>
标签。 现在我正在尝试使用<a>
标签。 我的问题是:有没有办法增加<a>
标签的可点击区域?比如,我将<a>
标签用于一个div框中,我希望整个div框成为一个按钮。我能否将点击区域更改为整个div框? 谢谢。
如果您想增加文本链接的点击区域,可以使用以下 CSS 代码:
a {
display: inline-block;
position: relative;
z-index: 1;
padding: 2em;
margin: -2em;
}
<a href="">An anchor element</a>
@t1m0thy的回答比我的更优雅。最好遵循他的建议。
此外,评论中@aldemarcalazans提供了一个不错的链接:https://davidwalsh.name/html5-buttons。
原始回答:
当需要链接时,请使用<a />
(即“anchor”的a)。当需要按钮时,请使用<button />
。
话虽如此,如果您确实需要扩展<a />
,请在其上添加CSS属性display: block;
。这样,您就可以指定它的宽度和/或高度(就像是一个<div />
一样)。
display:block
。然后你应该为<a />使用padding
,而不是为<a />的容器使用。 - Jaime Montoya如果您正在使用HTML5,那么您可以这样做,否则此代码将是无效的:
<a href="#foo"><div>.......</div></a>
block
:
#link {
display: block;
width: 100px;
height: 40px;
}
<a href="#foo" id="link">Click Here</a>
注意在将链接块级元素化之后,你才能应用 width
和 height
属性。
对我来说填充方案不好用,因为我在按钮上使用了边框,并且很难修改标记来创建触摸区域的叠加层。
所以我只是使用了:before伪元素来创建一个叠加层,在我的情况下非常完美,因为点击事件以同样的方式传播。
button.my-button:before {
content: '';
position: absolute;
width: 26px;
height: 26px;
top: -6px;
left: -5px;
cursor: pointer;
}
<button class="my-button">A button</button>
注意: 确保父元素具有 position:relative
属性。
z-index
。 - Arthur Khazbsposition: relative;
,否则 ::before
伪元素会随着布局的移动而改变位置(页面上有动画)。 - jimasun只需要将锚点设置为 display: block
和 width/height: 100%
。例如:
.button a {
display: block;
width: 100%;
height: 100%;
}
jsFiddle:http://jsfiddle.net/4mHTa/
如果您正在使用HTML 5,即文档类型
<!doctype html>
如果您想在 HTML 中创建块级链接,则可以使用块级链接。
<a href="google.com">
<div class="hello">
..
</div>
</a>
将 padding
添加到锚点标签的 CSS 类中。如果需要,根据所需的可点击区域单独添加 padding-top
、padding-bottom
等。这对我很有效。
提供更多的左侧、底部、右侧和顶部空间。这样可以增加锚点标签的可点击/可触摸区域,方便点击...
记住:这也可能会产生负面影响。
a {
text-decoration: none;
font-size: 12px;
min-width: 10px !important;
padding: 0px 1px !important;
margin-right: 3px;
position: relative;
z-index: 50;
}
a:before {
position: absolute;
content: '';
top: -10px;
right: -10px;
left: -10px;
bottom: -10px;
z-index: 40;
}
<a href="">An anchor</a>
我发现最干净的解决方案是使用::before
,因为我不想改变并可能使HTML
复杂化。这里有一个例子:
// the parent element
.chevron {
position: relative;
width: 36px;
height: 36px;
border-radius: 18px;
cursor: pointer;
}
// the background covers only 36px as of the parent
.chevron:hover {
background: #F1FBFE;
}
// the invisible "touch area"
.chevron::before {
position: absolute;
width: 48px;
height: 48px;
top: -6px; // half of parent's height
content: '';
}
其他属性,如left
、cursor
、z-index
并不是必需的。特别是cursor
会从父元素继承,因为pseudo-element
位于父元素下方(即使它延伸得更远)。
下面的图片显示了鼠标尚未进入父元素,但仍会触发:hover
(添加background
)和cursor: pointer
。
padding: 0 2em; margin: 0 -2em;
以防止可点击区域被向下推。 - Gringo Suavebox-sizing: content-box
,因为它被 Bootstrap 重置为border-box
。 - Cyril Durand