热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

纯CSS解决方案,用于将项目分割为动态数量的列-PureCSSsolutionforsplittingitemsintoadynamicamountofcolumns

Isthereawaytoalignitemsinseveralcolumns,wherethenumberofcolumnsdependsonthewidest

Is there a way to align items in several columns, where the number of columns depends on the widest item? Both the item height and the container width are fixed, but the item width is dynamic.

是否有一种方法可以将多个列中的项对齐,其中列的数量取决于最宽的项?项目高度和容器宽度都是固定的,但是项目宽度是动态的。

I am looking for a CSS-only way to achieve the following behavior:

我正在寻找一种只有css的方法来实现以下行为:

(Assume that the parent container is 300px wide.)

(假设父容器的宽度为300px)

  • If the widest item is wider than 150px, use a single column
  • 如果最宽的项大于150px,则使用一列
  • If the widest item is between 100px and 150px, use two columns
  • 如果最宽的项在100px到150px之间,使用两列
  • If the widest item is less than 100px, use three columns
  • 如果最宽的项小于100px,则使用三列
  • ...
  • If the widest item is less than container width / N, use N columns
  • 如果最宽项小于容器宽度/ N,则使用N列

One possible way to have this behavior could be by using display:inline-block and setting width property to the width of the widest element in the container using Javascript.

有一种可能的方法是使用display:inline-block,并在容器中使用Javascript将宽度属性设置为最宽的元素的宽度。

See this JSFiddle for an example:

请看这个JSFiddle,示例是:

Example

However, I am thinking that there should also be a CSS-only way of doing this. Is it possible?

然而,我认为也应该有一种css的方式来做这件事。是可能的吗?

If not, perhaps there is an elegant CSS-only way of distributing / snapping the dynamically-sized items to the columns in a container with a fixed width?

如果没有,也许有一种优雅的仅使用css的方式,将动态大小的项目分配到具有固定宽度的容器中的列中?

7 个解决方案

#1


25  

...I am looking for a CSS-only way to achieve the following behavior...If the widest item is wider than...

…我正在寻找一种只有css的方法来实现以下行为……如果最宽的项比…

...I am thinking that there should also be a CSS-only way of doing this...

…我认为应该有一种只有css才能做到的方式……

As indicated by @Paulie-D, CSS can't detect varying widths in your child divs and hence a pure CSS only solution is not existent.

正如@Paulie-D所指出的,CSS无法检测子div中不同的宽度,因此不存在纯的CSS唯一解决方案。

This is because you are wanting to get the widths of all elements, then get the max of those, and then use that width to distribute elements into columns. This computation is beyond CSS. You will need Javascript to do that.

这是因为您希望获得所有元素的宽度,然后获得它们的最大值,然后使用该宽度将元素分配到列中。这种计算超出了CSS。这需要Javascript来实现。

If not, perhaps there is an elegant CSS-only way of distributing / snapping the dynamically-sized items to the columns in a container with a fixed width?

如果没有,也许有一种优雅的仅使用css的方式,将动态大小的项目分配到具有固定宽度的容器中的列中?

I will explain that in two parts:

我将分两部分来解释:


Part 1, the CSS:

When we say that we want content to be in columns, it means a top-to-down flow instead of just left-to-right wrapping flow. For this we require CSS Columns.

当我们说我们希望内容在列中,它意味着一个自上而下的流,而不是仅仅从左到右的包装流。为此,我们需要CSS列。

The trick would be to specify auto for column-count / column-width. This will automatically distribute the content into the number of columns required within the parent width.

诀窍是为列数/列宽指定auto。这将自动将内容分配到父宽度中所需的列的数量。

I made a fundamental mistake in the above statement (hence another edit). As per the specs here the algorithm says:

我在上面的语句中犯了一个根本性的错误(因此又一次编辑)。根据这里的规格,算法说:

(01) if ((column-width = auto) and (column-count = auto)) then
(02)      exit; /* not a multicol element */ 

This is where I was wrong earlier. When both column-count and column-width are set to auto then it is treated as not a multicol element. When one of these properties is set to non-auto value, then the other property is determined by this one.

这是我之前错误的地方。当列数和列宽都设置为自动时,它就被视为非多列元素。当其中一个属性被设置为非自动值时,另一个属性由这个属性决定。

From the above ref:

从上面的参考:

if column-count is set to auto, then the number of columns will be determined by other properties (e.g., column-width, if it has a non-auto value) and if column-width is set to auto, then the column width will be determined by other properties (e.g., column-count, if it has a non-auto value)

如果将列数设置为auto,那么列的数量将由其他属性决定(例如,列宽,如果它有非自动值),如果列宽设置为auto,那么列宽将由其他属性决定(例如,如果列宽没有自动值,那么列数)

An example would be to set column-width to a fixed-width, say 120px (we will deal that in part 2 a little later):

例如,将列宽设置为一个固定的宽度,比如120px(稍后我们将在第2部分中对此进行讨论):

.container { -webkit-columns: auto 120px; columns: auto 120px; }

This will cause the container to fit the content in as many columns as it can for a column width of 120px within its own width. If you increase the container width, it will get more columns. If you decrease the container width, it will get less columns eventually collapsing to a single column when there is not much space available.

这将使容器在其自己的宽度为120px的列中尽可能多地容纳内容。如果您增加容器的宽度,它将获得更多的列。如果减少容器的宽度,当没有足够的空间时,最终压缩到单个列的列就会减少。

See the complete example in snippet below:

参见下面代码片段中的完整示例:

Example 1:

示例1:

* { box-sizing: border-box; padding: 0; margin: 0; }
p { margin-left: 16px; }
.container { width: 400px; border: 1px solid #f00; margin: 16px; }
.container.col { -webkit-columns: auto 120px; columns: auto 120px; }
.container > div { 
	-webkit-column-break-inside: avoid; column-break-inside: avoid; 
	display: block; padding: 8px; border: 1px solid #ccc;
}
#one { width: 200px; }
#two { width: 300px; }

Small Container (1-column):

Maudie Mcmanus
Remedios
Chaya B
Duncan
Lashonda

Medium Container (2-column):

Maudie Mcmanus
Remedios
Chaya B
Duncan
Lashonda

Large Container (3-column):

Maudie Mcmanus
Remedios
Chaya B
Duncan
Lashonda

Fiddle 1: http://jsfiddle.net/abhitalks/tgwp4b7a/2/show

小提琴1:http://jsfiddle.net/abhitalks/tgwp4b7a/2/show

In the above snippet, we are using column-count: auto on the container, and an arbitrary column-width: 120px (just for demo). It is all there is to it. There are three examples in the code above: (1) where container is of small width and content is distributed in one columns as they are constrained by the column-width; (2) where container is of medium width and content is distributed in two columns as there is now more space available; and (3) where container is of much larger width and can accommodate three columns.

在上面的代码片段中,我们在容器上使用了column-count: auto,以及一个任意的column-width: 120px(仅供演示)。这就是一切。在上面的代码中有三个例子:(1)容器的宽度很小,内容分布在一个列中,因为它们受到列宽的约束;(2)容器中等宽度,内容以两列形式分布,空间更大;(3)容器的宽度大得多,可以容纳三列。

As a side-effect, if the container's width is in percent, then the whole apparatus automatically becomes responsive as well. On larger screens showing more columns, and on smaller screens collapsing to one column.

作为副作用,如果容器的宽度是百分比,那么整个设备也会自动响应。在显示更多列的大屏幕上,在缩小为一列的小屏幕上。

However, this is dependent on the fixed-width that you give to the container's column-width and hence can also be called a magic-number solution. But, this is not what we want. We do not want to determine columns based on container's width, we want the columns to be determined by the content width. We'll see how to eliminate that dependency in the part 2 that follows.

但是,这依赖于容器的列宽的固定宽度,因此也可以称为魔术数字解决方案。但是,这不是我们想要的。我们不希望根据容器的宽度来确定列,我们希望这些列由内容宽度决定。我们将在下面的第2部分中看到如何消除这种依赖性。


Part 2, extending it with Javascript:

Now that we have established that elements can be distributed automatically by CSS in columns depending on the width available on parent, we can extend this to eliminate our dependence on fixed-width via Javascript.

既然我们已经确定了元素可以由CSS根据父元素的宽度自动地以列的形式分布,那么我们就可以扩展它,通过Javascript消除对固定宽度的依赖。

Coming back to your question of:

回到你的问题:

...If the widest item is wider than...

…如果最宽的项比…

In order to determine the widest item and apply that width to the rest of them, all that you require is just a well-known two-liner Javascript:

为了确定最宽的项并将该宽度应用于其他项,您所需要的只是一个众所周知的两行Javascript:

var maxWidth = Math.max.apply(null, $("div.item").map(function () {
    return $(this).width();
}).get());

We also set child divs to inline-block prevent wrapping to identify the real width. So, all you have to add to the CSS we wrote in part 1 is this:

我们还将子div设置为inline-block防止包装以识别真正的宽度。所以,你要添加到我们在第1部分中所写的CSS中:

.container > div {
    display: inline-block; 
    white-space: nowrap;   /* prevents wrapping and helps getting actual width */
}

Then we need to do two things: (1) set the column-width on container to this max-width that we calculated above; and (2) set this width to all of the child div to allow them to stack neatly. Also, we will not be needing column-count / column-width to be set in CSS, because we have to do that in Javascript anyway.

然后我们需要做两件事:(1)将容器上的列宽设置为上面计算的最大宽度;并且(2)将此宽度设置为所有子div,以允许它们整齐地堆叠。同样,我们也不需要在CSS中设置列数/列宽,因为我们必须在Javascript中这样做。

$("#container").css({ "column-width": maxWidth }).find('div').width(maxWidth);

See the complete example in snippet below:

参见下面代码片段中的完整示例:

Example 2:

示例2:

//large
	var maxWidth = Math.max.apply(null, $("#one > div").map(function () { return $(this).outerWidth(); }).get());
	$("#one").css({ "-webkit-column-width": maxWidth, "column-width": maxWidth }).find('div').outerWidth(maxWidth);

	// medium
	var maxWidth2 = Math.max.apply(null, $("#two > div").map(function () { return $(this).outerWidth(); }).get());
	$("#two").css({ "-webkit-column-width": maxWidth2, "column-width": maxWidth2 }).find('div').outerWidth(maxWidth2);

	// small
	var maxWidth3 = Math.max.apply(null, $("#three > div").map(function () { return $(this).outerWidth(); }).get());
	$("#three").css({"-webkit-column-width": maxWidth3, "column-width": maxWidth3 }).find('div').outerWidth(maxWidth3);
* { box-sizing: border-box; padding: 0; margin: 0; }
	p { margin-left: 16px; }
	.container { width: 450px; border: 1px solid #f00; margin: 16px; }
	.container > div { 
		-webkit-column-break-inside: avoid; column-break-inside: avoid; 
		display: inline-block;  white-space: nowrap;
		padding: 8px; border: 1px solid #ccc;
	}

	

Normal children (wrapping):

Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

Large children (1-column):

Maudie Mcmanus Mcmanus Mcmanus
Remedios
Chaya B
Duncan
Lashonda

Medium children (2-column):

Maudie Mcmanus Mcmanus
Remedios
Chaya B
Duncan
Lashonda

Small children (3-column):

Maudie Mcmanus
Remedios
Chaya B
Duncan
Lashonda

Fiddle 2: http://jsfiddle.net/abhitalks/ojd57678/4/show

小提琴2:http://jsfiddle.net/abhitalks/ojd57678/4/show

(Changed the above snippet and fiddle. Thanks to @Yandy_Viera, who pointed out the fact that jQuery .outerWdith should be used instead of .width (which ignores box-sizing: border-box, causing incorrect widths to be set.)

(更改了上面的代码片段并进行了修改。感谢@Yandy_Viera,他指出了jQuery . outerwdith应该被使用的事实,而不是。width(忽略了框的大小:边界框,导致设置不正确的宽度)。

In the above snippet, we are now using three variations of examples: (1) where child divs are of larger width and are distributed in one column as they are constrained by the container's width; (2) where child divs are of smaller width and are distributed in two columns as there is now more space available; and (3) where child divs are of very small width and can be accommodated in three columns.

在上面的代码片段中,我们现在使用了三种不同的示例:(1)子divs的宽度较大,并且由于受容器宽度的限制而分布在一列中;(2)子divs的宽度较小,并且由于现在有更多的空间,因此被分成两列;和(3)子div的宽度非常小,可以容纳在三列中。


As you can see, CSS can help in distributing content into columns based on available width but cannot calculate and apply widest of the element widths to each of them. For this a two-liner Javascript would get you done what you initially wanted.

正如您所看到的,CSS可以根据可用的宽度将内容分发到列中,但是不能计算并将最宽的元素宽度应用到每个列中。为此,两行Javascript将完成您最初需要的工作。

Note: When I first read your question I was under the impression that you already have a working Javascript solution with you, and I wasn't sure if you wanted one. However, on a second read I realized that you hadn't, and the Javascript angle was essential to understand. Hence, this edit to add a Javascript part.

注意:当我第一次读到您的问题时,我感觉您已经有了一个可用的Javascript解决方案,我不确定您是否需要它。然而,在第二次阅读时,我意识到您没有这样做,理解Javascript的角度非常重要。因此,此编辑将添加一个Javascript部分。

Note 2: There was a flaw in the previous version of this answer, where I let in a fundamental mistake in auto values of the columns properties. This necessitated another edit.

注意2:在这个答案的前一个版本中有一个缺陷,我在列属性的自动值中犯了一个根本性的错误。这需要另一个编辑。

#2


9  

As well all they said in comments, do not exist a CSS-only solution so I wanted to leave you a nice solution using js in which you do not even have to iterate looking for the widest item, everything comes from a set of CSS and math.

同样,他们在评论中说的,不存在一个只有CSS的解决方案,所以我想给你们留下一个使用js的很好的解决方案,在这个解决方案中,你甚至不需要迭代查找最宽的项,所有的东西都来自于CSS和math。

You can change the contents of the elements and you will see how the number of columns are adjusted, if the widest item is less than container width / N, it will use N columns automatically.

您可以更改元素的内容,您将看到如何调整列的数量,如果最宽的项小于容器宽度/ N,它将自动使用N列。

Check out this JSFiddle for demo

检查这个JSFiddle以获得演示

The idea is very simple, you set width: 'auto', display: 'inline-block' to container to allow it to fit its contents which is defined by the width of the widest element see it in the bellow img:

这个想法很简单,你设置宽度:'auto', display: 'inline-block'给容器,让它适合它的内容它的内容是由最宽元素的宽度定义的见下面的img:

enter image description here

Now you can use the width of container to know the width of widest item and this avoid you to have to iterate seeking it. Right now you can use this width to setting to the rest of items but let's do it a little better we can make elements occupy the entire width of the container just with a litter calc:

现在,您可以使用容器的宽度来知道最宽项的宽度,这就避免了您必须重复查找它。现在你可以用这个宽度来设置其他的项目但是我们做得更好一点我们可以让元素占据整个容器的宽度就像一个空的calc:

var div = Math.floor(initialWidth / widestItemWidth);     /*this is to get as many items fit with the width of the widest element*/
var itemWidth = initialWidth / div;      /*for the width of the item occupy the entire container*/

So if the widest item is less than container width / N, it will use N columns automatically and they will fit the width of container, that is all you have to do, just set a css property, do a little calc and there you have what you wanted to achieve.

如果最宽的项小于容器宽度/ N,它将使用N列自动适合集装箱的宽度,你所要做的,只是设置一个css属性,做一些钙,你有什么你想实现。

$(document).ready(function() {
    var $cOntainer= $('.container');
    var $item = $('.item');

    var initialWidth = $container.outerWidth();

   $container.css({     /*to allow it to fit its contents which is defined by the width of the widest element*/
        width: 'auto',
        display: 'inline-block'
    });   

    var widestItemWidth = $container.outerWidth();     /*Now this is the width of the widest item*/

    var div = Math.floor(initialWidth / widestItemWidth);     /*this is to get as many items fit with the width of the widest element*/
    var itemWidth = initialWidth / div;      /*for the width of the item occupy the entire container*/
  
  /*if you don't want the items occupy the entire width of the container just use 'widestItemWidth' as width of $item*/

    $item.css({
        width: itemWidth,
        float: 'left'
    });
    $container.css({     /*restoring the initial styles*/
        width: initialWidth,
        display: 'block'
    });
})
.container {
  width: 400px;
  overflow: hidden;
}
.container .item {
  padding: 8px;
  border: 1px solid rgb(216, 213, 213);
}
*{
  box-sizing: border-box;
}

Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

If you want to add margin to your items you just have to take it into account when you do the math like this:

如果你想在你的项目中增加保证金你必须把它考虑进去当你这样做的时候:

$(document).ready(function() {
    var $cOntainer= $('.container');
    var $item = $('.item');

    var initialWidth = $container.outerWidth();

    $container.css({
            width: 'auto',
            display: 'inline-block'
        });

    var currentWidth = $container.outerWidth();
    var itemMargin= parseInt($item.css('margin-right'));

    var div = Math.floor(initialWidth / currentWidth);
    var itemWidth = initialWidth / div - itemMargin;   /*subtracting the item's margin from the compute width*/

    $item.css({
        width: itemWidth,
        float: 'left'
    });
    $container.css({
        width: initialWidth,
        display: 'block'
    });
})
.container {
  width: 400px;
  overflow: hidden;
}
.container .item {
  padding: 8px;
  border: 1px solid rgb(216, 213, 213);
  margin-right: 3px;
}
*{
  box-sizing: border-box;
}

Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

Here a JSFiddle example to play with

这里有一个JSFiddle示例

#3


4  

The closest you can probably get with a pure CSS solution is to use CSS columns as suggested by others (or CSS Grid approach - See Edit). But, the key is to use relative units and be very aware of the location and of your column container in your layout and use media queries to control column count. This is definitely NOT a bulletproof solution. However, if you are creating the layout and control the placement and scope of the column container element then you can control the column count fairly reliably. If this is for a widget that is out of your control you will indeed need to implement a Javascript based solution.

使用纯CSS解决方案最接近的可能是使用别人建议的CSS列(或CSS Grid方法——参见编辑)。但是,关键是要使用相对单元,并且要非常了解布局中的位置和列容器,并使用媒体查询来控制列计数。这绝对不是一个防弹的解决方案。但是,如果您正在创建布局并控制列容器元素的位置和范围,那么您可以相当可靠地控制列计数。如果这是一个超出您控制范围的小部件,那么您确实需要实现一个基于Javascript的解决方案。

Reference Links: Responsive CSS Columns, CSS Grid Layout

参考链接:响应性CSS列,CSS网格布局

EDIT: After reading your question again and looking at your screenshot example, it looks as though you are actually looking for a common CSS grid grid solution where the elements flow horizontally and not vertically. I updated my answer to include a snippet demo of this where the blocks re-flow horizontally.

编辑:在再次阅读您的问题并查看您的屏幕截图示例之后,看起来您实际上是在寻找一个普通的CSS网格解决方案,其中元素是水平流的,而不是垂直流的。我更新了我的答案,其中包含了块水平流的演示片段。

Snippet Demo with Columns based Media Queries and Container Widths (approximate minimum column width of 10em):

带基于列的媒体查询和容器宽度的代码片段演示(大约最小列宽度为10em):

#main, #sideBar {
    box-sizing:border-box;
    display:block;
    padding:0;
    margin:0;
    width:100%;
}

.container {
    width: 100%;
    min-width:10em;
    -webkit-columns: 1;
    -moz-columns: 1;
      columns: 1;
}
.container .item {
    display: block;
    padding: 8px;
    border: 1px solid rgb(216, 213, 213);
    box-sizing:border-box;
    -webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */
          page-break-inside: avoid; /* Firefox */
               break-inside: avoid; /* IE 10+ */
}
@media only screen and (min-width:20em) {
    .container {
    -webkit-columns: 2;
    -moz-columns: 2;
      columns: 2;
    }
}

@media only screen and (min-width:32em) {
    #main {
        float:left;
        width:65%;
    }

    #sideBar {
        float:left;
        width:30%;
        margin-left:5%;
    }
    #sideBar .container {
    -webkit-columns: 1;
    -moz-columns: 1;
      columns: 1;
    }

}

@media only screen and (min-width:48em) {
    
    #main .container {
    -webkit-columns: 3;
    -moz-columns: 3;
      columns: 3;
    }

    #sideBar .container {
    -webkit-columns: 1;
    -moz-columns: 1;
      columns: 1;
    }

}

@media only screen and (min-width:52em) {
    
    #sideBar .container {
    -webkit-columns: 2;
    -moz-columns: 2;
      columns: 2;
    }

}

@media only screen and (min-width:100em) {
    
    #main .container {
    -webkit-columns: 5;
    -moz-columns: 5;
      columns: 5;
    }

    #sideBar .container {
    -webkit-columns: 3;
    -moz-columns: 3;
      columns: 3;
    }

}

#main

Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

EDIT: Added this Snippet Demo using a CSS Grid approach that re-flows the blocks horizontally instead of vertically.

编辑:使用CSS Grid方法添加这个演示片段,该方法水平地而不是垂直地重新流块。

#main, #sideBar {
    box-sizing:border-box;
    display:block;
    padding:0;
    margin:0;
    width:100%;
    clear:left;
}

.container {
    width: 100%;
    min-width:10em;
}

.container .item {
    display: block;
    float:left;
    padding: .5em;
    border: 1px solid rgb(216, 213, 213);
    box-sizing:border-box;
    vertical-align: top;

}

@media only screen and (min-width:20em) {
    .container .item {
        margin: 0 1%;
        width:48%;
    }
}

@media only screen and (min-width:32em) {
    #main {
        float:left;
        width:65%;
    }

    #sideBar {
        float:left;
        clear:none;
        width:30%;
        margin-left:5%;
    }
    

    #sideBar .container .item {
        margin: 0;
        width:100%;
    }

}

@media only screen and (min-width:48em) {
    
    #main .container .item {
        width:31%;
    }

}

@media only screen and (min-width:52em) {
    
    #sideBar .container .item {
        margin: 0 1%;
        width:48%;
    }


}

@media only screen and (min-width:100em) {
    
    #main .container .item {
        width:18%;
    }

    #sideBar .container .item {
        width:31%;
    }

}

#main

Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

#4


2  

Well as many others pointed it out here there is no CSS only solution. Mainly because CSS was designed to be loaded before the dom content so the content display nicely. Our main problem here is that we do NOT know the width of the element in advance, we will only know it when the page has loaded. Almost all the solutions on the page have the same idea, use Javascript to loop trough the elements, find the widest one and set all other elements (with the same class) to the given width. To improve the process and to make it a one line solution (with jquery, can be done with Javascript as well, but for simplicity I used jQuery), I suggest the following "hack / trick":

正如许多人指出的,这里没有CSS唯一的解决方案。主要是因为CSS被设计为在dom内容之前加载,所以内容显示得很好。我们这里的主要问题是,我们不事先知道元素的宽度,只有在页面载入时才知道。页面上的几乎所有解决方案都有相同的想法,使用Javascript对元素进行循环,找到最宽的元素,并将所有其他元素(具有相同的类)设置为给定的宽度。为了改进流程并使其成为一行解决方案(使用jquery也可以使用Javascript完成,但为了简单起见,我使用了jquery),我建议使用以下“hack / trick”:

1) Do not define the width of your container, and set the display to table rather than block;

1)不定义容器的宽度,将显示设置为table而不是block;

2) Do not set any width for the items inside the div

2)不要为div中的项设置任何宽度。

This will make the items have the same width and display in one column, so when we use jQuery to get the max width we do not need to loop trough the elements.

这将使条目具有相同的宽度,并在一列中显示,因此当我们使用jQuery获得最大宽度时,我们不需要通过元素循环。

Now use jQuery to inject additional CSS rules into the document header for the container and for the items. We need to change the container display type back to block instead of table, set it's width to 400px (or whatever we need) and we need to make the items inline-blocks with a set width.

现在,使用jQuery将附加的CSS规则注入到容器和项目的文档头中。我们需要将容器显示类型更改为块,而不是表,将其宽度设置为400px(或我们需要的任何东西),并需要将项目设置为宽度的内联块。

Since CSS is always applying the last property this will be quite easy:

因为CSS总是应用最后一个属性,这很简单:

$("").appendTo("head");

I have updated your Fiddler example HERE

我在这里更新了您的Fiddler示例

I have tested it in IE 12, Edge, Chorme and Firefox and it works in all the browsers.

我在IE 12、Edge、Chorme和Firefox中测试过它,在所有浏览器中都可以使用。

EDIT 1

编辑1

If you do not want to use jQuery to keep the page as light as possible you can use the following one liner Javascript as well:

如果您不想使用jQuery来保持页面尽可能轻,那么您可以使用以下一行Javascript代码:

document.head.innerHTML += "";

Quick explanation: container clientWidth will include the padding and the border of the items, since the padding in the original example is 8px and the border is 1px we need to deduct it twice (one time left one time right) from the width of the container.

快速说明:容器clientWidth将包含填充和项目的边框,因为原始示例中的填充是8px,边框是1px,我们需要从容器的宽度中减去它两次(一次左,一次右)。

See updated Fiddle

看到更新的小提琴

EDIT 2

编辑2

A complete HTML document:

一个完整的HTML文档:




  
  






      
Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

#5


1  

First of all- Check out the Fiddle Demo (play with the .container's width...)

首先-检查小提琴演示(播放.container的宽度…)

This is not possible using CSS only, but here is an elegant solution using jquery, that detects the container's width, the widest item's width, and spread the items into the relevant number of columns (dynamically created).

仅使用CSS是不可能的,但这里有一个使用jquery的优雅解决方案,它可以检测容器的宽度、最宽项的宽度,并将条目分散到相关的列(动态创建)中。

HTML

HTML

Without width:

Maudie Mcmanus
Remedios Arrington
Chaya B
Duncan
Lashonda Tatum Walls

Javascript

Javascript

$(function(){
    var $items = $('.item');

    // detect the widest column's width
    var widestItemWidth = 0;
    $items.each(function(){
        widestItemWidth = Math.max(widestItemWidth, $(this).width());
    });

    // calculate the number of columns
    var $cOntainer= $('.container');
    var cOntainerWidth= $container.width();
    var numOfColumns = parseInt(containerWidth / widestItemWidth);

    // create the columns
    for(var i = 0; i 
'); } var $columns = $('.column'); $columns.css('width', (100/numOfColumns)+'%'); // spread the items between the columns $items.each(function(i){ var columnIndex = i % numOfColumns; $(this).appendTo($columns.eq(columnIndex)); }); });

CSS

CSS

.container {
    width: 400px;
}
.container .column {
    display: inline-block;
    box-sizing: border-box;
    vertical-align: text-top;
}
.container .item {
    display: inline-block;
    padding: 8px;
    border: 1px solid rgb(216, 213, 213);
}

#6


0  

The easiest would seem to set width to 32% plus clear:none for all columns and a separate clear:both class per every third (last) column. Add media queries to address different screen sizes and set width accordingly, e.g. 24%, 48%, etc.

最简单的方法似乎是将宽度设置为32%加上clear:对于所有的列和一个单独的清除都没有:两个类(最后一个)列。添加媒体查询来处理不同的屏幕大小,并相应地设置宽度,例如24%、48%等。

#7


0  

Try this example

试试这个例子

@media only screen and (device-width : 300px) {#container {width:300px; display:block;}}
@media only screen and (device-width : 150px) {#container {width:150px; display:block; float:left}}
@media only screen and (device-width : 100px) {#container {width:150px; display:block; float:left}}

推荐阅读
author-avatar
mobiledu2502882663
这个家伙很懒,什么也没留下!
Tags | 热门标签
RankList | 热门文章
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有