首页 > 解决方案 > 如果我缩放元素,为什么我不能居中

问题描述

我正在使用它在 CSS 中居中:

.testclass {
display: flex;
justify-content: center;
}

但是当我想使用widthand缩放元素时height,它不起作用并且我的元素没有居中。

像这样:

.testclass {
display: flex;
justify-content: center;
width: 200px;
height: 200px;
}

有什么问题?

标签: htmlcssclass

解决方案


这看起来像预期的行为。

请记住,在这种情况下justify-content: center;,将容器内的内容居中 - 而不是容器本身。

编辑:我添加margin: 0 auto;到容器的中心。

#container1 {
  display: flex;
  justify-content: center;
  border: 1px solid red;
}

#container1 > div {
  border: 1px solid blue;
  background: yellow;
}

#container2 {
  display: flex;
  justify-content: center;
  border: 1px solid red;
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

#container2 > div {
  border: 1px solid blue;
  background: yellow;
}
<div id="container1">
  <div>test 1</div>
</div>
<div id="container2">
  <div>test 2</div>
</div>


推荐阅读