为什么 HREF 标签中的 IMG 标签没有对齐的边框



<a>标签中的<img>标签永远存在。
为什么他们的边界不排队??

假设页面上的唯一内容是

<a href='#'><img src='images/x.png' border='0'></a>

当我在Firefox调试器中查看它时,它们都具有相同的宽度(图像的宽度(。

但是,图像在 y=0,h=img 的高度。

然而,a 标签的 y 低于 0(可能是图像的一半??(,并且高度使其比图像低几个像素。

为什么会这样??

它稍后会抛弃布局,使一切变得混乱。

默认情况下,图像的底部位于<a>元素的文本基线处。 基线下方的额外空间用于降序(在下面延伸的字母形式的部分,例如字母 p 和 q。

您可以通过在图像上使用"垂直对齐:底部"或"文本底部"来对齐元素底部的图像:

a {border: 1px solid #00F}
img#two {vertical-align: bottom}
img#three {vertical-align: text-bottom}
Image at baseline:
<a href='#'><img src='http://placehold.it/50x50'></a>
Image at bottom:
<a href='#'><img id="two" src='http://placehold.it/50x50'></a>
Image at text-bottom:
<a href='#'><img id="three" src='http://placehold.it/50x50'></a>

(规则不是同义词:text-bottom将元素定位在"父元素字体的底部",bottom放置在"元素的底部"。基于这里的问题,"底部"可能是技术上正确的,但正如下面的评论中所述,至少对于某些用户/浏览器,它可以重叠边框......

该问题与呈现<a><img>的默认方式有关。 锚链接(默认情况下(是inline元素,而图像是inline-block的。

解决任何换行/间距问题的最简单方法是调整显示样式。 将<a>设置为 inline-block,并将子<img>设置为 block 。 请考虑以下示例图示,这些元素在组合时呈现的"默认"方式与更改其默认 CSS 时的"默认"呈现方式。

a {
  border: 1px solid black;
}
img {
  border: 1px solid red;  
}
.correct-display {
  display: inline-block;
  margin-top: 20px; /* Push the 2nd example down so the <a> border is visible on the 1st example */
}
.correct-display img {
  display: block;
}
<a href="#null">
  <img src="http://placehold.it/300x150" />
</a>
<a href="#null" class="correct-display">
  <img src="http://placehold.it/300x150" />
</a>

最新更新