本篇文章给大家分享的是有关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"> 亿速云左对齐<br /> 亿速云<br /> 亿速云<br /> php </div> <div class="TextRight"> 亿速云右对齐<br /> 亿速云<br /> 亿速云<br /> php </div> <div class="TextCenter"> 亿速云居中对齐<br /> 亿速云<br /> 亿速云<br /> php </div> <div class="TextJustify"> 亿速云<br /> 两端对齐<br /> 亿速云<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>

以上就是CSS如何实现文本左对齐、右对齐和居中对齐,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。