Is the CSS3 transform translate percentage values

2020-07-13 10:22发布

I think it is true that when we do a CSS3 transform translate using a percentage value, then that percentage is relative to its own width or height, so (50%, 75%) means 50% of its own width, 75% of its own height, but I can't find any specs that say that.

Example: https://jsfiddle.net/cstsyw3s/1/
using:

transform: translate(100%, 100%)

I looked into http://www.w3.org/TR/css3-transforms but can't find it mentioned there -- I could only find such as for transform-origin, the "percentages: refer to the size of bounding box", and I think the bounding box probably is rectangle with the element's width and height. (not including any border)... but I can't find a definition for bounding box except for SVG and table either.

3条回答
霸刀☆藐视天下
2楼-- · 2020-07-13 10:46

Yes you are right. Transform translate moves an element either a certain number of pixels if using px or a percentage of the size of the element being moved if using %.

So if you had a div class='mover' this css would move the div 250px on the x and y axis.

.mover {width: 100px;
height: 100px;
-webkit-transform: translate(250%, 250%);
background: #000;}

Here is a simple jsfiddle to play around with as an example.

查看更多
虎瘦雄心在
3楼-- · 2020-07-13 10:59

In this section http://www.w3.org/TR/css3-transforms/#transform-property it states:

Percentages: refer to the size of bounding box

The definition of bounding box is (source)

A bounding box is the object bounding box for all SVG elements without an associated CSS layout box and the border box for all other elements. The bounding box of a table is the border box of its table wrapper box, not its table box.

And border box is (source)

The width and height properties include the padding and border, but not the margin. Note that padding and border will be inside of the box e.g. .box {width: 350px; border: 10px solid black;} lead to a box rendered in the browser of width: 350px.

I hope this helps

查看更多
手持菜刀,她持情操
4楼-- · 2020-07-13 11:01

In chrome (tested in v59), the percentage is calculated based on the dimension of the bounding box plus the border.

If an element has a width of 200px, and border of 50px, and we apply something like transform: translate(100%, 0) The total translated distance is 200px + 50*2 = 400px.

In this case, if you want the translating distance to be 100px, you can always add a box-sizing:border-box

section {
  width:400px;
  height:400px;
  background: #f0ad4e;
}

span {
  display:block;
  background:red;
  width:200px;
  height:200px;
  border:100px solid black;
  transform: translate(100%, 0);
}
<section>
  <span class="center">hello world</span>
</section>

Example: https://jsfiddle.net/httcg329/1/

查看更多
登录 后发表回答