【问题标题】:Fill the entire area inside a big square (a div) with little squares, based on their quantity根据数量,用小方块填充大方块(div)内的整个区域
【发布时间】:2017-08-27 15:51:27
【问题描述】:

我想通过使用 css3 来解决它,可能使用 flexbox 或 grid 或其他类似的框架。

我的标记:

<div class="square">
  <div class="smaller-square">
  <div class="smaller-square">
  <div class="smaller-square">
  <div class="smaller-square">
</div>

我将控制的内盒数量 (Q)。 Q = i2,其中 i = 0...N

【问题讨论】:

  • 欢迎您。至少向我们展示你尝试过的东西,无论是基于 Flexbox 还是网格布局,比如 N=1..3(1、4 和 9 个小方块)
  • Quantity queries 接近你想要达到的目标
  • 我创建了 CodePen 来更清楚地解释它。请阅读 CodePen js 部分中的评论。 CODEPEN

标签: css grid flexbox


【解决方案1】:

更新版本:

当您从用户那里获取输入时,每次使用 onchange 事件来获取输入标签的值。

HTML:

<input onchange="fillSquare()" id="quantity"  type="number" min="0"/> //You can use any input type

Javascript:

function fillSquare(){
   var Q = $("#quantity").val();
   var i = Math.sqrt(Q); // Here I'm taking square root of 'Q' to calculate width and height of small sqaures.
   $('.smaller-square').css({
     "width": (100% / i),
     "height": (100% / i)
   });
}

旧解决方案:

我认为 CSS 中的 calc 属性更适合您的要求。

首先确保你有一些像下面这样的 css 来制作它们。

.square{
   display:block;
   width: 500px; //Any number is fine, until both height and width are same
   height: 500px; //Make sure you've some numbers here, as we are going to deal with width and height of smaller-square in percentages
}
.smaller-square{
   display:inline-block;
   float:left;
}

现在您可以通过两种方式实现此目的,一种是纯 CSS(您要求的那种),另一种是使用一些 Javascript 库。

首先,CSS:

.smaller-square{
   width:calc(100% / i);
   height:calc(100% / i);
}

这里你必须硬编码 i 值,这意味着你在执行代码之前知道 i 值。 例如,如果 i=2 那么,

.smaller-square{
   width:calc(100% / 2);
   height:calc(100% / 2);
}

.smaller-square的宽度和高度是.square宽度和高度的50%

【讨论】:

  • 您好,您的解决方案非常接近我的需要。谢谢你。但它缺乏非常重要的时刻——我重视硬编码。应该是 .smaller-squares in .square. So it should be dynamic value. Maybe you have an idea how to do it (count smaller-squares) 数量的平方根?
  • 请告诉我,你如何决定数量(Q)?你是硬编码还是从 javascript 中获取?
  • 我从 javascript 中获取它。为了对用户更特别(使用选择标签),比我用 .smaller-square(s) 填充 .square
  • 然后您可以使用 Javascript 函数更改选择标记输入。因为没有 javsscipt 功能,您无法决定宽度和高度等 CSS 属性。如果你对此没问题,我会给你修改后的解决方案。
  • 是的,没问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2013-05-24
  • 2017-12-15
  • 1970-01-01
  • 2022-01-09
相关资源
最近更新 更多