為什么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 elementoratomic inline-level elementetc,但不包括inline element.

#


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM