Tailwind CSS - 文本对齐
Tailwind CSS:响应式文本对齐
Section titled “Tailwind CSS:响应式文本对齐”Tailwind 提供了一套全面的实用工具类,用于控制文本的水平对齐。这些工具完全响应式,让你能够轻松地将排版适应不同的屏幕尺寸。
核心文本对齐类
Section titled “核心文本对齐类”这些类直接对应于 text-align CSS 属性。
| 类名 | CSS 属性 |
|---|---|
| text-left | text-align: left; |
| text-center | text-align: center; |
| text-right | text-align: right; |
| text-justify | text-align: justify; |
| text-start | text-align: start; |
| text-end | text-align: end; |
逻辑属性:text-start 和 text-end
Section titled “逻辑属性:text-start 和 text-end”对于现代的、国际化的应用程序,使用逻辑属性是最佳实践。text-start 和 text-end 根据文档的书写方向(从左到右 LTR vs. 从右到左 RTL)对齐文本。
text-start:在从左到右(LTR)的语言(如英语)中将文本左对齐,在从右到左(RTL)的语言(如阿拉伯语)中将文本右对齐。text-end:在 LTR 语言中将文本右对齐,在 RTL 语言中将文本左对齐。- 最佳实践:优先使用
text-start和text-end而不是text-left和text-right,以使你的网站更具可访问性且更易于本地化。
实践中的响应式对齐
Section titled “实践中的响应式对齐”Tailwind 最强大的功能之一是响应式地应用实用工具。一个常见的模式是在移动设备上文本居中,而在大屏幕上左对齐。
示例:响应式英雄区 (Hero Section)
Section titled “示例:响应式英雄区 (Hero Section)”在此示例中,所有文本默认居中。在中等屏幕 (md) 及更大尺寸上,文本对齐方式会变为 text-left。
<div class="bg-slate-100 dark:bg-slate-800 p-8 rounded-lg"> <div class="max-w-4xl mx-auto text-center md:text-left"> <h2 class="text-3xl font-bold text-slate-900 dark:text-white sm:text-4xl"> Responsive by Default </h2> <p class="mt-4 text-lg text-slate-600 dark:text-slate-400"> This component's text is centered on mobile screens. On screens wider than 768px, it becomes left-aligned. This common UI pattern is trivial to implement with Tailwind's responsive variants. </p> <div class="mt-6"> <a href="#" class="inline-block bg-indigo-600 text-white font-semibold px-5 py-3 rounded-md hover:bg-indigo-500"> Get Started </a> </div> </div></div>两端对齐文本
Section titled “两端对齐文本”text-justify 实用工具将文本均匀分布到每一行,创建整洁、块状的边缘。它最适合用于多行段落文本。
示例:两端对齐的文章文本
Section titled “示例:两端对齐的文章文本”<div class="max-w-2xl mx-auto p-4"> <h1 class="text-2xl font-bold mb-4 text-start">The Art of Typography</h1> <p class="text-justify text-gray-700 leading-relaxed"> Justified text can lend a formal, polished appearance to a block of content, reminiscent of a newspaper column or a printed book. It works by adjusting the spacing between words in each line so that the left and right edges of the text block are flush. While visually neat, it's important to ensure it doesn't create distracting 'rivers' of white space, which can impair readability. Use it thoughtfully for dense, paragraph-heavy content. </p></div>如果你的文本对齐没有按预期工作,请检查父容器。文本对齐是继承的。此外,确保文本元素是块级元素(如 <p>, <h1>, <div>)或行内块级元素,并且它在其父元素中有足够的空间进行对齐。你不能将文本居中在一个与文本本身宽度完全相同的容器内。