Hãy thử fiddle này http://jsfiddle.net/zbbHc/45/
Không chắc, nhưng tôi nghĩ đây là tối đa chúng tôi có thể làm bằng CSS một mình.
Cập nhật: (điều này sẽ không làm việc trong mọi trường hợp, kiểm tra mã dưới đây mà làm việc trong mọi trường hợp [Tôi đoán])
HTML
<div class="wrapper">
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB hide"></div>
<div class="iB hide"></div>
</div>
CSS
.wrapper {
width: 100%;
background: red;
text-align: center;
text-align-last: left;
}
.iB {
display:inline-block;
width: 200px;
height: 100px;
background: green;
}
.iB.hide {
visibility:hidden;
}
Đây là phương pháp nhanh và bẩn bằng jQuery. Điều này sẽ thêm các yếu tố vô hình tự động
Fiddle đây http://jsfiddle.net/fD6fn/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="lib/jquery-1.6.2.min.js"></script>
<style>
.wrapper {
width: 100%;
background: red;
text-align: center;
text-align-last: left;
}
.iB {
display:inline-block;
width: 200px;
height: 100px;
background: green;
}
.iB.hide {
visibility:hidden;
}
</style>
</head>
<body>
<div class="wrapper" id="wrapper">
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
<div class="iB"></div>
</div>
<script language="javascript">
function findHiddenElementCount() {
var $wrapper = $("#wrapper"),
itemWidth = "200",
count = "",
itemCount = 7;
count = $wrapper.width()/itemWidth;
// Some wild logic below, can be optimized.
return parseInt(count) - (itemCount - (parseInt(itemCount/parseInt(count)) * parseInt(count))) ;
}
function addInvisibleElements()
{
// Delete invisible items
$("#wrapper .iB.hide").remove();
var c = findHiddenElementCount();
for(var i = 0; i < c;i++)
{
$("#wrapper").append('<div class="iB hide"></div>');
}
}
$(window).bind("resize",addInvisibleElements); // resize handler
$(document).ready(addInvisibleElements); // take care during page load
</script>
</body>
</html>
Rất thú vị, tôi tự hỏi nếu điều này có thể được thực hiện với CSS tinh khiết – Kos
Trình bao bọc của bạn rộng bao nhiêu? Có vấn đề bao nhiêu mặt hàng trên một hàng? – JohnC
Câu hỏi hay! Là một mở rộng cho câu hỏi của @JohnC, khi bạn nói không muốn áp dụng chiều rộng cố định cho wrapper của bạn, bạn có nghĩa là bạn không muốn đặt chiều rộng cố định cho hai "cột"? –