首页 > 解决方案 > 如何使 div 缩小以适应容器保持其相对宽度?

问题描述

#container {
  height: 500px;
  width: 500px;
  background-color: blue;
}

#container>div {
  background-color: rgb(36, 209, 13);
  height: 100px;
}

#one {
  width: 1000px;
}

#two {
  width: 800px;
}
<div id="container">
  <div id="one"></div>
  <div id="two"></div>
</div>

这就是没有收缩的样子。

#container {
  height: 500px;
  width: 500px;
  background-color: blue;
}

#container>div {
  background-color: rgb(36, 209, 13);
  height: 100px;
}

#one {
  width: 500px;
}

#two {
  width: 400px;
}
<div id="container">
  <div id="one"></div>
  <div id="two"></div>
</div>

这是与。在不手动调整宽度的情况下执行此操作的最佳方法是什么?我尝试使用 flexbox,flex-direction: column;但每行只有一个项目不会缩小。我也不想使用transform: scaleX(0.5);或类似的东西。所有这些都应该自动适应。

标签: javascripthtmlcss

解决方案


如果我正确理解您的问题,我会将 div(一和二)的宽度设置为百分比而不是固定值。这样,它们将始终具有相对于其容器的宽度。

#container {
  height: 500px;
  width: 600px;
  background-color: blue;
}

#container>div {
  background-color: rgb(36, 209, 13);
  height: 100px;
}

#one {
  width: 100%;
}

#two {
  width: 80%;
}
<div id="container">
  <div id="one"></div>
  <div id="two"></div>
</div>


推荐阅读