CSS :after伪类元素实现文字两端对齐
以前很多人都这么干过:两个字中间使用 来隔开达到四个字的宽度,三个字也可以,但是,如果文字中包含有数字、大小写英文字母时,比如 “122账号”“abc密码” 这样的,就不好计算该用几个空格了。
现在 CSS3 中可以使用 text-align: justify 样式来实现这个效果。
例如,如下登录界面,需要实现“用户名:” 和 “密码:”文本的两端对齐效果。
<body>
<article>
<header>用户登录</header>
<main>
<section>
<label>用户名</label>:
<input type="text" name="userName" id="userName">
</section>
<section>
<label>密码</label>:
<input type="password" name="password" id="password">
</section>
</main>
</article>
</body>
一种不建议的方式,是借助其他的 html 行内空标签 来实现,比如、等等,是可以达到预期的效果的,具体实现如下:
section label {
width: 70px;
display: inline-table;
text-align: justify;
}
label span{
display:inline-block;
/*padding-left: 100%;*/
width:100%;
}
padding-left: 100%和width:100%都可以达到效果,选用其一即可。
以上这种方式,由于代码中加入的其他无意义的 html 标签,没有实际作用,只是用途 CSS 样式 的布局,有点儿违反了结构表现分离的原则,所以建议使用 CSS3 中的 after、before伪元素:
另外一种方式,就是使用 CSS3 中的 after、before伪元素:
section label {
width: 70px;
display: inline-table;
text-align: justify;
}
/*label span{ display:inline-block; !*padding-left: 100%;*! width:100%; }*/
section label:after {
content: " ";
display: inline-block;
width: 100%;
}
以上实现的效果是一样的,但没有使用多余的 html 标签来做布局。
完整的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS 实现文字两端对齐</title>
<style type="text/css"> article { text-align: center; } header { margin-top: 200px; margin-bottom: 20px; font-size: 24px; font-weight: bold; } section { height: 50px; line-height: 50px; } section label { width: 50px; display: inline-table; text-align: justify; } /*label span{ display:inline-block; !*padding-left: 100%;*! width:100%; }*/ section label:after { content: ""; display: inline-block; width: 100%; } section input { height: 20px; letter-spacing: 2px; } </style>
</head>
<body>
<article>
<header>用户登录</header>
<main>
<section>
<label>用户名</label>:
<input type="text" name="userName" id="userName">
</section>
<section>
<label>密码</label>:
<input type="password" name="password" id="password">
</section>
</main>
</article>
</body>
</html>
还没有评论,来说两句吧...