<a> tag fills up entire page width?

时间:2018-04-06 20:17:46

标签: html css

Here's some very simple HTML

.box {
  width: 300px;
  height: 500px;
  background-color: #fff;
}

.box img {
  width: 300px;
  height: 425px;
}
<a href="#" class="box-a">
  <div class="box">
    <img src="movies.jpg">
    <span>Title</span>
  </div>
</a>

But, for some reason, when I run this code, the <a> tag fills up the entire width of the page. Does anyone know why this is, and how i could prevent it in the future?

1 个答案:

答案 0 :(得分:1)

默认情况下,您的<a>是内联元素,因为div是display: block元素,它将填充整个页面。

你有两种方法可以离开这里:

  • 您可以将其更改为display: inline-block,您的链接只会在您的框中填充;
  • 或者您可以为max-width设置<a>并将其设为display: block

a.box-a{
    display: inline-block
}

a.box-b{
    max-width: 300px;
    display: block;
}

.box {
  width: 300px;
  height: 500px;
  background-color: #fff;
}
.box img {
  width: 300px;
  height: 425px;
}
<a href="#" class="box-a">
  <div class="box">
    <img src="movies.jpg">
    <span>Title</span>
  </div>
</a>

<a href="#" class="box-b">
  <div class="box">
    <img src="movies.jpg">
    <span>Title</span>
  </div>
</a>

如果display: inline-block兼容性符合您的项目标准,请检查caniuse.com,如果没有,请转到display: block; max-width: 300px解决方案。