文本的位置在网页布局中是必不可少的,今天的这篇文章就来给大家分享关于使用CSS实现文本左对齐、右对齐和居中对齐的方法,下面我们来看具体的内容。
要设置文本对齐(左对齐,右对齐,居中对齐)需要用到的CSS属性是text-align属性。(相关推荐:CSS学习手册)
语法格式:
text-align :(文本位置)
| 位置 | 说明 |
| left | 左对齐 |
| right | 右对齐 |
| center | 居中对齐 |
| justify | 两端对齐 |
接下我们来分别看看这四种对齐方式的设置方法
文本左对齐的设置方法:
text-align:left;
文本右对齐设置方法:
text-align:right;
文本居中对齐设置方法:
text-align:center;
文本两端对齐设置方法:
text-align:justify;
我们来看具体的代码示例1:
TextAlign.html
<!DOCTYPE html><html><head> <meta charset="utf-8" /> <link rel="stylesheet" href="TextAlign.css" /> <title></title> </head> <body> <div class="TextLeft"> php中文网左对齐<br /> php中文网<br /> php中文网<br /> php </div> <div class="TextRight"> php中文网右对齐<br /> php中文网<br /> php中文网<br /> php </div> <div class="TextCenter"> php中文网居中对齐<br /> php中文网<br /> php中文网<br /> php </div> <div class="TextJustify"> php中文网<br /> 两端对齐<br /> php中文网<br /> php </div> </body> </html>
TextAlign.css
.TextLeft{ margin-top:24px; margin-left:32px; border:1px solid #ff6a00; width:480px; text-align:left;}.TextRight { margin-top: 24px; margin-left: 32px; border: 1px solid #ff6a00; width: 480px; text-align: right;}.TextCenter { margin-top: 24px; margin-left: 32px; border: 1px solid #ff6a00; width: 480px; text-align: center;}.TextJustify { margin-top: 24px; margin-left: 32px; border: 1px solid #ff6a00; width: 480px; text-align: justify; text-justify: distribute-all-lines;}显示结果
使用Web浏览器显示上述HTML文件。将显示如下所示的效果。

代码示例2:
文本左对齐:
<!DOCTYPE html><html><head><title></title><meta charset="utf-8"><style type="text/css">.leftText{ text-align:left; }</style></head><body><div class="leftText">左对齐</div></body></html>文本右对齐:
<!DOCTYPE html><html><head><title></title><meta charset="utf-8"><style type="text/css">.rightText{ text-align:right; }</style></head><body><div class="rightText">右对齐</div></body></html>居中对齐:
<!DOCTYPE html><html><head><title></title><meta charset="utf-8"><style type="text/css">.centerText{ text-align:center; }</style></head><body><div class="centerText">居中对齐</div></body></html>本篇文章到这里就全部结束了,更多关于文本对齐的内容大家可以关注php中文网的CSS视频教程栏目!!!










