一、前言
對(duì)于前端,多行二端對(duì)齊是個(gè)常見(jiàn)的需求,也非常簡(jiǎn)單,但多加幾個(gè)限制條件就比較有意思
了。一個(gè)是完美的二端對(duì)齊(上端有個(gè)border做參照)、二個(gè)兼容ie9、三是有margin。
二、對(duì)于第一個(gè),不考慮ie,有margin,自然是flex,示例代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多行二端對(duì)齊</title>
<style>
.main1 {
width: 50%;
margin: 0 auto;
margin-top: 100px;
border-top: 1px solid black;
overflow: hidden;
}
.container1 {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
margin-top: 20px;
margin-right: -3%;
}
.item1 {
/*box-sizing: border-box;*/
flex: 0 0 22%;
display: inline-block;
margin-top: 1%;
margin-right: 3%;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="main1">
<div class="container1">
<div class="item1"></div>
<div class="item1"></div>
<div class="item1"></div>
<div class="item1"></div>
<div class="item1"></div>
<div class="item1"></div>
<div class="item1"></div>
</div>
</div>
</body>
</html>
注意事項(xiàng):?jiǎn)涡杏杏疫吘嗫梢灾苯佑胘ustity-content:space-between。但如果itme1超過(guò)一行并且數(shù)量不定,在最后一行出現(xiàn)item1不滿一行的情況就不能用了。
關(guān)鍵代碼:.container1 { margin-right: -3%; },利用margin百分比相對(duì)于父元素的特性。
二、考慮ie,有margin,示例代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>二端對(duì)齊</title>
<style>
.item {
display: inline-block;
width: 22%;
height: 100px;
background-color: pink;
margin: 0 3% 1% 0;
}
.main {
width: 50%;
margin: 0 auto;
margin-top: 100px;
border-top: 1px solid black;
overflow: hidden;
}
.container {
font-size: 0;
margin-top: 20px;
margin-right: -3%;
}
</style>
</head>
<body>
<div class="main">
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
</body>
</html>
此方法和第一種flex沒(méi)有本質(zhì)的區(qū)別,但是具有兼容性。