Skip to content

Tailwind CSS - 边框圆角

Tailwind 的 rounded-* 工具类提供了一种简单而强大的方式来为元素应用圆角。从微妙的边缘柔化到创建完美的圆形,这些类是现代 UI 设计的常用样式。

你可以为所有角、特定侧面甚至单个角应用圆角。

类前缀示例描述
rounded-{size}rounded-lg为所有四个角应用相同的圆角。
rounded-{side}-{size}rounded-t-lg为特定侧面应用圆角。t(上),b(下),l(左),r(右)。
rounded-{corner}-{size}rounded-tl-lg为单个角应用圆角。tl(左上),tr(右上),bl(左下),br(右下)。

{size} 可以是 sm、md、lg、xl、2xl、3xl,或者 full 来创建完美的圆形或药丸状。

最佳实践: 为了国际化(支持从左到右和从右到左的文本方向),建议使用逻辑属性:rounded-s-*(起始)和 rounded-e-*(结束)。这些属性在 RTL(从右到左)语言中会自动翻转。例如,rounded-s-lg 在 LTR(从左到右)语言中等同于 rounded-l-lg,在 RTL 语言中等同于 rounded-r-lg。

让我们构建几个常见的 UI 组件,看看不同的圆角工具类如何在实践中使用。

<div class="p-8 bg-slate-100 font-sans">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 items-start">
<!-- 1. 按钮 -->
<div class="space-y-4">
<h3 class="font-semibold text-lg">按钮</h3>
<button class="px-4 py-2 bg-blue-600 text-white font-semibold rounded-md shadow-md hover:bg-blue-700">中等圆角</button>
<button class="px-6 py-3 bg-green-600 text-white font-semibold rounded-full shadow-md hover:bg-green-700">药丸状</button>
</div>
<!-- 2. 头像 -->
<div class="space-y-4 text-center">
<h3 class="font-semibold text-lg">头像</h3>
<img src="/path/to/avatar.jpg" alt="用户头像" class="w-24 h-24 mx-auto object-cover rounded-full border-4 border-white shadow-lg">
</div>
<!-- 3. 具有不同圆角样式的卡片 -->
<div class="space-y-4">
<h3 class="font-semibold text-lg">卡片</h3>
<div class="bg-white shadow-lg rounded-xl p-6">
<p>一张具有大尺寸统一圆角(`rounded-xl`)的卡片。</p>
</div>
<div class="bg-white shadow-lg rounded-t-xl p-6">
<p>一张仅顶部带圆角(`rounded-t-xl`)的卡片。</p>
</div>
</div>
<!-- 4. 输入框 -->
<div class="space-y-4">
<h3 class="font-semibold text-lg">输入框</h3>
<input type="text" placeholder="默认圆角" class="w-full p-2 border border-slate-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
<input type="text" placeholder="无圆角" class="w-full p-2 border border-slate-300 rounded-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
</div>
<!-- 5. 消息气泡 -->
<div class="space-y-4">
<h3 class="font-semibold text-lg">聊天气泡</h3>
<div class="bg-blue-500 text-white p-3 rounded-t-2xl rounded-bl-2xl max-w-xs">
<p>你好!这里使用了多个单独的角圆角类。</p>
</div>
</div>
</div>
</div>

你可以轻松地在 tailwind.config.js 中添加自己的 border-radius 尺寸,以匹配你的项目设计系统。

tailwind.config.js
module.exports = {
theme: {
extend: {
borderRadius: {
'4xl': '2rem', // 32 像素
'5xl': '2.5rem', // 40 像素
}
}
}
}

重新构建后,你就可以在 HTML 中使用 rounded-4xl 等类了。

  • 内容溢出: 如果圆角容器内的子元素(例如顶部的 <img> 标签)不遵循父元素的曲线,其尖角可能会“戳出”容器。通过对带圆角的父容器应用 overflow-hidden 来解决此问题。
  • 表格中的边框合并: 当对使用合并边框的表格应用圆角时,圆角可能不会显示。一个常见的解决方案是使用 border-separate,并对 <td> 和 <th> 元素单独管理边框。