Html <a> tag stretching to entire page width

时间:2016-10-07 15:26:22

标签: html css

I just made a nice little button <div> wrapped in a link tag <a>. The problem is that the a tag stretches to the whole width of the page. I have no idea of how and why this happend since it haven't occoured for me before. I'll leave a codepen link and a snippet down here. Thanks in advance guys! PS Note that the icons are just placeholders for the real ones! Don't judge them!

http://codepen.io/JohanSundman/pen/kkxbLg

&#13;
&#13;
/*
.archive-link {
  width: 120px;/* Same as the button width *//*
  display: block;
}
*/

.archive-button {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  
  width: 120px;
  height: 40px;
  transition: all 200ms ease-in-out;
}

.archive-button::after {
  content: "";
  display: inline-block;
  width: 15px;
  height: 100%;
  background-color: #ae3535;
  /* Stacking context */
  position: absolute;
  z-index: -1;
  /*Transition*/
  transition: width 250ms;
}

.archive-button:hover::after {
  width: 100%;
}

.archive-button-down {
  background-image: url('https://image.freepik.com/free-icon/arrow-down-angle_318-52905.jpg');
  background-size: auto 100%;
  background-position: center;
  background-repeat: no-repeat;
}

.archive-button-up {
  background-image: url('https://image.freepik.com/free-icon/ascendant-chevron-arrow-up_318-28667.jpg');
  background-size: auto 100%;
  background-position: center;
  background-repeat: no-repeat;
}

.archive-button:hover {
  background-position: center;
}
&#13;
<a href="http://www.swiftpeak.net/">
  <div class="archive-button archive-button-down"></div>
</a>


<br><br>

<a href="http://www.swiftpeak.net/">
  <div class="archive-button archive-button-up"></div>
</a>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

<a>标记是内联元素,<div>标记是块级元素。

块级元素扩展到其父元素的宽度。在这种情况下,<div>迫使<a>成为全宽。您可以使用.archive-button修改下面的display: inline-block;课程,以减轻您所看到的全角行为!

来自[MDN] [1]:

  

块级与内联

     

块级元素和内联元素之间存在一些关键差异:

     

格式

     

默认情况下,块级元素从新行开始,但内联元素可以从一行中的任何位置开始。

     

内容模型

     

通常,块级元素可以包含内联元素和其他块级元素。这种结构上的区别固有的理念是,块元素会产生更大的&#34;更大的&#34;结构而不是内联元素。

修改:或者,您也可以取消内部<div>元素,并直接将.archive-button应用于<a>标记。然后,您要避免对<div>标记中<a>的非法性发表评论。