给定 Flex 布局中的缩略图列表,如果 Flex 容器具有可变宽度,是否可以仅使用 CSS 来定位每行的第一个和最后一个元素?
.thumbnails {
display: flex;
margin: 0;
padding: 0;
list-style-type: none;
flex-flow: row wrap;
}
.thumbnail {
width: 250px;
height: 250px;
margin: 5px;
background: #ccc;
border: 1px solid #000;
}
<ul class="thumbnails">
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
</ul>
Flexbox 很棒,但有时很难处理。
这里有 JQuery 脚本的更新版本,用于使用弹性布局定位每行的第一个子级和最后一个子级:
// Call the function anytime needed, by default on loading and resizing window, see below
function flexboxRowLastChild(){
$(document).ready(function(){
//For each element with class="flexbox-wrapper"
$('.flexbox-wrapper').each(function() {
//Reset at every function call
$(this).children('.flexbox-row-first-child').removeClass('flexbox-row-first-child');
$(this).children('.flexbox-row-last-child').removeClass('flexbox-row-last-child');
//Set :first-child and :last-child (or use css pseudo-element instead)
$(this).children().eq(0).addClass('flexbox-row-first-child');
$(this).children().eq($(this).children().length - 1).addClass('flexbox-row-last-child');
var rowWidth = $(this).children().eq(0).outerWidth(true);
//For counting number of row if needed
var nbrRow = 1;
for (var i = 0; i < $(this).children().length; i++) {
if (rowWidth <= $(this).width()) {
//Sum of every children width (with margin) while it's less than the flexbox-wrapper width
var rowWidth = rowWidth + $(this).children().eq(i+1).outerWidth(true);
} else {
//Set the flexbox-row-first-child and flexbox-row-last-child classes and begin to check for a new row
$(this).children().eq(i-1).addClass('flexbox-row-last-child');
$(this).children().eq(i).addClass('flexbox-row-first-child');
var nbrRow = nbrRow + 1;
var rowWidth = $(this).children().eq(i).outerWidth(true) + $(this).children().eq(i+1).outerWidth(true);
}
}
});
});
}
$(document).ready(function(){
// Call the function on window load
flexboxRowLastChild();
// Call the function on window resize
$(window).resize(function(){
flexboxRowLastChild();
});
});
.flexbox-wrapper {
display: flex;
margin: 0;
padding: 0;
list-style-type: none;
flex-flow: row wrap;
}
.thumbnail {
width: 100px;
height: 100px;
margin: 5px;
background: #ccc;
border: 1px solid #000;
}
.thumbnail.flexbox-row-first-child {
background: #000;
}
.thumbnail.flexbox-row-last-child {
background: #444;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<ul class="flexbox-wrapper">
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
</ul>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)