今天在項目中碰到了設計盒子兩端對齊的栗子,我們用inline-block方法輕鬆的解決了,下面是個人經驗:
原理: 利用文字text-align:justify; 操縱inline-block盒子,可以實現盒子兩端對齊。
說明: inline-block元素 會按照基線對齊的方式兩列,給這個元素的父盒子設置一個text-align:justify; 便可實現兩端對齊的功能
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>盒子兩端對齊</title> 6 </head> 7 <style type="text/css"> 8 * { 9 margin: 0; 10 padding: 0; 11 } 12 html,body { 13 width: 100%; 14 height: 100%; 15 } 16 .box { 17 width: 100%; 18 height: 100%; 19 /* 設置元素兩端對齊 */ 20 text-align: justify; 21 } 22 /* 這裏的僞元素必定要加上,否則span元素不能兩端對齊 */ 23 .box:after { 24 content: ""; 25 display: inline-block; 26 overflow: hidden; 27 width: 100%; 28 } 29 .box span { 30 width: 50px; 31 height: 50px; 32 /* 設置盒子爲行內塊 */ 33 display: inline-block; 34 background-color: skyblue; 35 /* 設置盒子內元素水平居中 */ 36 text-align: center; 37 /* 設置盒子內容垂直居中 */ 38 line-height: 50px; 39 } 40 </style> 41 <body> 42 <div class="box"> 43 <span>1</span> 44 <span>2</span> 45 <span>3</span> 46 <span>4</span> 47 <span>5</span> 48 </div> 49 </body> 50 </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>盒子兩端對齊</title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height: 100%;
}
.box {
width: 100%;
height: 100%;
/* 設置元素兩端對齊 */
text-align: justify;
}
/* 這裏的僞元素必定要加上,否則span元素不能兩端對齊 */
.box:after {
content: "";
display: inline-block;
overflow: hidden;
width: 100%;
}
.box span {
width: 50px;
height: 50px;
/* 設置盒子爲行內塊 */
display: inline-block;
background-color: skyblue;
/* 設置盒子內元素水平居中 */
text-align: center;
/* 設置盒子內容垂直居中 */
line-height: 50px;
}
</style>
<body>
<div class="box">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>
</body>
</html>css
從小就喜歡看科幻片,特別是電影裏面幾行代碼就可以得到,而後解救全世界的神祕的人,固然最感興趣的就是代碼自己了html