Flexbox justify-content not working properly with transform scale

有些话、适合烂在心里 提交于 2019-12-24 00:16:15

问题


I have a regular unordered list of items with display: flex and justify-content: space-between applied to it (as a result, .first_item touches the left edge of .list and .last_item touches the right edge of .list):

<ul class='list'>
    <li class='first_item'>Item</li>
    <li class='middle_item'>Item</li>
    <li class='last_item'>Item</li>
</ul>

However, if I shrink the items using transform: scale(0.5), there is now a space at these two locations, as if justify-content: space-between was "unaware" that the items have been reduced.

This isn't right: even when shrinking the items, the first and last item should still touch the left and right edges of the container.

What's going on and how to fix that problem?


回答1:


Once you scale down the element with the transform, it is automatically centered within its box.

This is because the initial value of the transform-origin property is 50%, 50% (i.e., centered horizontally and vertically).

As a result, the items are offset from the edges of the container.

.list {
  display: flex;
  justify-content: space-between;
  border: 1px dashed black;
  padding: 0;
  list-style: none;
}

li {
  transform: scale(0.5);
  border: 1px solid red;
}
<ul class='list'>
  <li class='first_item'>Item</li>
  <li class='middle_item'>Item</li>
  <li class='last_item'>Item</li>
</ul>

You can adjust the position of the transformed element with left and right on transform-origin.

.list {
  display: flex;
  justify-content: space-between;
  border: 1px dashed black;
  padding: 0;
  list-style: none;
}

.first_item {
  transform: scale(0.5);
  transform-origin: left;
}

.last_item {
  transform: scale(0.5);
  transform-origin: right;
}

li {
  transform: scale(0.5);
  border: 1px solid red;
}
<ul class='list'>
  <li class='first_item'>Item</li>
  <li class='middle_item'>Item</li>
  <li class='last_item'>Item</li>
</ul>

More details in the spec: https://drafts.csswg.org/css-transforms/#transform-origin-property



来源:https://stackoverflow.com/questions/43020800/flexbox-justify-content-not-working-properly-with-transform-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!