让盒子两端对齐小技巧 => inline-block

时间:2023-03-08 16:20:01
今天在项目中碰到了设计盒子两端对齐的栗子,咱们用inline-block方法轻松的解决了,下面是我的经验:
  原理: 利用文字text-align:justify; 操纵inline-block盒子,能够实现盒子两端对齐。
  说明: inline-block元素 会按照基线对齐的方式两列,给这个元素的父盒子设置一个text-align:justify; 即可实现两端对齐的功能
 <!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>
    

<!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>


 

从小就喜欢看科幻片,特别是电影里面几行代码就能够获得,然后解救全世界的神秘的人,当然最感兴趣的就是代码本身了