为什么transform对行内元素不生效
Posted fayin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么transform对行内元素不生效相关的知识,希望对你有一定的参考价值。
注:赶时间的同学可直接下拉到底,看结论。
我使用transform
对一个元素进行位移,代码如下:
<div class="box">
<span>今天你吃了么?</span>
</div>
// css
span {
transform: translateX(20px)
}
然而span
标签并没有向右移动20px
,这使我感到困惑。
但当我给span
增加display: inline-block
时,transform
又表现正常了——span
向右位移了20px
。
transform
不支持行内元素么?
此时必须google
一下啊,果不其然,早有前辈提出了相同的问题:css3-transform-not-working
其中一个回答引用了w3c
关于transform
的规范:
CSS Transforms Module Level 1 - Transformable Element
A transformable element is an element in one of these categories:
- an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption [CSS2]
- an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, patternTransform or gradientTransform [SVG11].
上面说到能够transform
的元素有哪些。其中提到atomic inline-level element
(原子行内级元素,嗯,翻译就是如此蹩脚),难不成span、a
等行内元素不属于原子行内级元素?
原子行内级元素是什么
An inline box is one that is both inline-level and whose contents participate in its containing inline formatting context. A non-replaced element with a ‘display‘ value of ‘inline‘ generates an inline box. Inline-level boxes that are not inline boxes (such as replaced inline-level elements, inline-block elements, and inline-table elements) are called atomic inline-level boxes because they participate in their inline formatting context as a single opaque box. (https://www.w3.org/TR/CSS2/visuren.html#x13)
上面这段话讲了两个盒子:inline box
(行内盒子)和inline-level box
(行内级盒子):
- 行内盒子由一个
display:inline
的非替换元素生成。 - 行内级盒子又叫做原子行内级盒子,它不是 行内盒子。因为它是透明的。
结论
因为,
display: block: 让一个元素生成一个block box
display: inline-block: 生成一个inline-level block container
,元素本身被格式化为atomic inline-level box
,它的内部被格式化为block box
display: inline: 让一个元素生成一个或多个inline boxes
而,可被transform
的元素有:block-level element
oratomic inline-level element
etc,但不包括inline element
.
#
以上是关于为什么transform对行内元素不生效的主要内容,如果未能解决你的问题,请参考以下文章