css内联块div定位

时间:2013-01-25 22:53:28

标签: positioning css

我正在尝试在响应式设计中解决一个假设问题。

我有一个容器div,包含4个(但可能更多或更少)显示为内联块的div。我想知道如何在页面调整大小时控制每行的div数(如果可能的话,使用CSS)。例如,当4个容器不再适合容器时,最后一个容器移动到第二行。在这种情况下,我想在第一行中有2个容器,在第二行中有2个容器。我不知道该怎么做。欢迎你的帮助!

编辑: 它也可能是6个容器,如果布局是: - 如果适合的话,1行6块 - 2行3块 - 3行2块 - 6行一个

集装箱的数量是可变的。我只是希望每行有相同数量的容器

html:

<div class="container"> 
   <div class="containee"></div>
   <div class="containee"></div>
   <div class="containee"></div>
   <div class="containee"></div>
</div>

css:

.containee {
  width:200px;
  height:200px;
  display:inline-block;
  background-color:tomato
}

这个例子可以在这里看到:http://cssdesk.com/uGLbq

(PS:我试图找到搜索网络的解决方案,但我真的不知道与此主题相关的好关键字)

4 个答案:

答案 0 :(得分:2)

你不能用CSS(AFAIK)。

您可以使用Javascript实时动态地进行“数学运算”。

在你的情况下,

  • 您知道一个区块的宽度(在那个时刻),
  • 您可以轻松获得窗口宽度( 时刻),
  • 你知道你的街区号码(那个时刻);

简单地应用((1)第一次打开页面,(2)每次块数改变,或(3)分辨率改变)以下代码中的算法:

// EXAMPLE OF INPUT
var windowWidth    = 1400;  // read it...
var blockWidth     = 200;   // read it or use const...
var numberOfBlocks = 10;    // read it... 


// Calculate the maximum number of blocks per row
var maxBlocksPerRow;
for (var i=0; i < numberOfBlocks; i++) {
   if ( (blockWidth * (i + 1)) > windowWidth){
      maxBlocksPerRow = i;
      break; 
   }
}

// Check the highest 0 module combination while iterating backwards
var magicNumberForMatchingBlocks = 1; // if not found, it will be 1.
for (var i = maxBlocksPerRow; i > 0 ; i--) {
   if ( (numberOfBlocks % i) == 0){
      magicNumberForMatchingBlocks = i;
      break;
   }
}

alert("With " + numberOfBlocks + " blocks, each one wide " + 
      blockWidth + " pixels, and a window wide " + windowWidth + " pixels, 
      the number of blocks per row for having always 
      the same number of block in any row is: " + magicNumberForMatchingBlocks);

然后使用该数字用Javascript填充或重新排列元素或更好地使用jQuery这样的Javascript库。

答案 1 :(得分:1)

HTML:

<div class="container">
    <div class="grouped">
        <div class="containee"></div>
        <div class="containee"></div>
    </div>
    <div class="grouped">
        <div class="containee"></div>
        <div class="containee"></div>
    </div>
</div>

的CSS:

.containee {
  width:200px;
  height:200px;
  display:inline-block;
  background-color:tomato
}
.grouped {
  float:left;
}

答案 2 :(得分:0)

试试这个:

.container
{
  min-width: 410px;
}

答案 3 :(得分:0)

如果页面适合4,则.containee一个float:left;,它们将位于彼此旁边,否则,您将拥有另一行div。如果你有另一条线,你也可以给它margin-top:5px;,第二条线的div不会被粘在第一行的div上。请注意,使用这种方法,它没有义务在每一行中具有相同数量的.containee,如果你有4,那么你重新调整大小,你将有3 - 1,然后是2 - 2 .. .etc ..

相关问题