Link的面积大于图像

Link's area greater than image

我正在尝试将一些图像放到我的网站上,这些图像将作为 hyperlink 到我页面的另一部分。问题是,当我使用 <a> 标签和 <img> 标签时,<a> 标签过度扩展了其左侧的 <img>,使我可以点击的区域成为一部分不希望被点击。我想将 <a> 标签保持在 <img>.

的范围内

这是我的代码:(抱歉,因为我是新手,所以我不知道如何以任何其他方式 post 它)

.firstproject {   
   height: 100px;
   width: 100px;
   background-color: red;
   margin-left: 100px;
}
<p><a class="firstproject" href="https://www.youtube.com/"><img 
class="firstproject" src="front.jpg"></a></p>

希望你能想通!

PS:我使用了红色背景,这样该区域就可以看到并且可以更好地看到它的延伸。 PS2:我用"youtube"地址作为link

的例子

为了将 a 标签的大小限制在定义的 class 范围内,我添加了 display: block 以确保应用 height/width(display: inline-block 也可以)。

我在下面的 link 中有两个示例,一个留有边距,一个保留边距,因为我不确定您在寻找什么。

https://jsbin.com/gahunohebu/edit?html,css,output

HTML:

<p><a class="firstproject" href="https://www.youtube.com/"><img 
class="firstproject" src="http://via.placeholder.com/350x150"></a></p>

  <p><a class="secondproject" href="https://www.youtube.com/"><img 
class="secondproject" src="http://via.placeholder.com/350x150"></a></p>

CSS:

.firstproject {
  height: 100px;
  width: 100px;
  background-color: red;
  margin-left: 100px;
  display: block;
}

.secondproject {
  height: 100px;
  width: 100px;
  background-color: red;
  display: block;
}

您可以在 CSS 技巧中阅读有关 CSS display 的更多信息:https://css-tricks.com/almanac/properties/d/display/

我所做的只是删除 margin-left: -100px;。我不知道此边距的原因是什么,但如果这对您的代码很重要,请告诉我并调整我的 awnser。

如果你想将图像向右移动更多,你可以使用以下 css:

position:relative;
left:25px;

有关详细信息,请参阅 CSS - Position

.firstproject {
  background-color: red;
  width:100px;
  height:100px;
}

.Secondproject{
  background-color: red;
  width:100px;
  height:100px;
  position:relative;
  left:50px;
}
<p>
  <a class="firstproject" href="https://www.youtube.com/"><img class="firstproject" src="front.jpg"></a>
</p>

<p>
  <a class="Secondproject" href="https://www.youtube.com/"><img class="firstproject" src="front.jpg"></a>
</p>

这是因为您的 img 元素和 a 上的边距。您可以将 a 元素的边距更改为 200px 并将其从 img 中删除以获得相同的结果,而不会 a 越界。

另外你不需要给a设置宽度和高度。它正在根据内容调整它的大小。

.firstproject-img {
  height: 100px;
  width: 100px;
  background-color: blue;
}

.firstproject-a {
  background-color: red;
  margin-left: 200px;
}
<p>
  <a class="firstproject-a" href="https://www.youtube.com/">
    <img class="firstproject-img" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
  </a>
</p>

您可以将 display: inline-block 应用到您的 a 标签,这会给您带来预期的结果。

要将图像包含在标签集图像 width100%

 
.firstproject {   
   height: 100px;
   width: 100px;
   background-color: red;
   display: inline-block;
}
.firstproject > img {
   width: 100%'
}
p {padding-left: 100px;}
<p><a class="firstproject" href="https://www.youtube.com/"><img 
class="firstproject" src="front.jpg"></a></p>

编辑: 要将 a 向右推,您可以将 padding-left 添加到它的父级

p {
    padding-left: 100px;
}