<a> hyperlink with div inside is to large / wide

时间:2016-11-16 15:22:50

标签: html html5 hyperlink tags margin

Surrounding a div with 'a' tag gives weird results, it feels the need to make the 'a' tag as wide as possible instead of the child size inside, i read it as something to do with HTML5.

Edge gives more or less the result i'm looking for, but in Chrome for some reason the 'a' tag is the full width of the page.

I would also like to include the div 'margin' within the 'a' tag. so i can't use the 'onclick' method. Can this be achieved without javascript? JSFiddle

<a href="http://example.com" style="background-color: #CCC;">
<div style="width: 100px; height: 100px; background-color: #C00; margin: 0px 8px 8px 0px; display:block;"><h2>text</h2></div>
</a>

<a href="http://example.com" style="background-color: #CCC;">
<div style="width: 100px; height: 100px; background-color: #C00; margin: 0px 8px 8px 0px;"><h2>text</h2></div>
</a>

<a href="http://example.com" style="background-color: #CCC;">
<div style="width: 100px; height: 100px; background-color: #C00; margin: 0px 8px 8px 0px; display:inline-block;"><h2>text</h2></div>
</a>

<a href="http://example.com" style="background-color: #CCC; display: block;">
<div style="width: 100px; height: 100px; background-color: #C00; margin: 0px 8px 8px 0px;"><h2>text</h2></div>
</a>

1 个答案:

答案 0 :(得分:2)

我立即找到的最简单的解决方法是使用另一个“div”标记围绕“a”标记,如下所示:

<div style="width: 100px">
    <a href="http://example.com" style="background-color: #CCC;">
        <div style="background-color: #C00; margin: 0px 8px 8px 0px;"><h2>text</h2></div>
    </a>
</div>

但是,为什么要将“a”标签放在div之外? div元素用于启用正确的间距,“a”标记实质上只是一个超链接。所以从逻辑上讲,你会将“a”标签放在div中,导致类似这样的东西:

<div style="background-color: #C00; margin: 0px 8px 8px 0px; width: 100px; height: 100px;">
  <a href="http://example.com" style="background-color: #CCC; display: inline-block; width: 100%; height: 100%;">
    <h2>text</h2>
  </a>
</div>

PS:我在这里使用内联CSS作为一个简单的例子,但你永远不应该使用它。而是使用CSS类。你以后会感谢我。