CSS缩放图像并对齐中心

时间:2019-04-03 11:40:04

标签: css flexbox

我的行宽为8格,彼此相邻。容器具有:

display: flex;
flex-wrap: wrap;

容器中的物品:

text-align: center;
flex: 1 1 0;
width: 0;

项目中的图像:

-webkit-transform: scale(0.5);
-moz-transform: scale(0.5);
-ms-transform: scale(0.5);
-o-transform: scale(0.5);
transform: scale(0.5);

所有项目的内部都有一个图像,现在我需要将这些图像对准div的中心。但是(我认为)由于比例尺代码的原因,它无法将它们精确地对准中心...有什么可以解决的吗?

致谢

1 个答案:

答案 0 :(得分:1)

您可以仅使项目成为弹性容器并将内容居中,如下所示:

.flex {
  display: flex;
  flex-wrap: wrap;
}

.item {
  border: 1px solid red; /* just so we can see the border */
  text-align: center;
  flex: 1 1 0;
  width: 0;
}

.image {
  -webkit-transform: scale(0.5);
  -moz-transform: scale(0.5);
  -ms-transform: scale(0.5);
  -o-transform: scale(0.5);
  transform: scale(0.5);
}

.fixed .item {
  display: flex;
  justify-content: center;
  align-items: center;
}
<h1>Original</h1>
<div class="flex">
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
</div>

<h1>Fixed</h1>
<div class="flex fixed">
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
  <div class="item">
    <img class="image" src="https://picsum.photos/100" />
  </div>
</div>