html - 为什么 anchor 标记不采用其包含元素的高度和宽度

标签 html css

这是我的 JsFiddle

当我使用 Chrome 开发者工具检查 anchor 标签的大小时,它显示第一个元素为 144px*18px,第二个元素为 310px*18px

我想知道为什么它不采用包含元素的高度和宽度以及它是如何计算的。

.gallery {
    background-color: #abcdef;
}
.gallery img {
    display: inline-block;
    margin-left: 20px;
    margin-top: 20px;
}
.normal {
    height: 160px;
    width: 110px;
    border: 5px solid black;
}
.wide {
    height: 160px;
    width: 280px;
    border: 5px solid black;
}
<div class="gallery">
    <a href="#"> <img class="normal" src=""> </a>
    <a href="#"> <img class="wide" src=""> </a>
</div>

最佳答案

CSS 2.1 spec

The dimensions of the content area of a box — the content width and content height — depend on several factors: whether the element generating the box has the 'width' or 'height' property set, whether the box contains text or other boxes, whether the box is a table, etc. Box widths and heights are discussed in the chapter on visual formatting model details.

<a>元素默认显示值为 inline .它的内容参与了布局,所以它是一个non-replaced。元素。

对于高度,规范说:

10.6.1 Inline, non-replaced elements

The 'height' property does not apply. The height of the content area should be based on the font, but this specification does not specify how.

所以 18px是从单行文本得出的,取自字体规范。较大的图像内容和包含的 block 大小都没有任何作用。

对于宽度,规范说

10.3.1 Inline, non-replaced elements

The 'width' property does not apply. A computed value of 'auto' for 'margin-left' or 'margin-right' becomes a used value of '0'.

换句话说,宽度由 <a> 决定元素的内容、填充、边框和边距。

对于第一个<a>元素为 114px(内容 - 图像加一个空格)+ 20px(左边距)+ 2x5px(左右边框)= 144px

对于第二个<a>元素为 280px(内容 - 图像)+ 20px(左边距)+ 2x5px(左右边框)= 310px

只需要考虑空格。元素在内联上下文中布置在行框中,因此第一个 <a> 开头的空格元素和第二个末尾<a>元素正在被丢弃。第一个<a>末尾的空格元素和第二个的开始 <a>元素正在折叠到一个空间中。当空格折叠时,它始终是第一个剩余的空格,在本例中是第一个 <a> 末尾的那个。元素,所以这就是为什么一个空格参与第一个宽度的原因 <a>元素,但不在第二个元素的宽度内。

关于html - 为什么 anchor 标记不采用其包含元素的高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18585069/

相关文章:

javascript - 使用 css 或 jquery、javascript 平均增加所有框的高度

php - 在循环中绘制空的虚拟列

javascript - 使用 jQuery 将事件附加到动态创建的选定选择

html - 如何从不透明度变化中排除边框

html - 类 no-gutter/相应的 CSS 不消除列之间的间隙

jquery - 让CSS背景图片不断改变jQuery来模仿闪烁

html - 使用css切 Angular 图像

jquery - SVG animateTransform 不适用于 FF 和 IE

html - CSS:删除滚动条并替换为表 <td> 中文本区域的可变高度

javascript - 我怎样才能使这个图像映射元素响应?