Skip to content

Tailwind CSS - 轮廓样式

Tailwind CSS 中的 outline-style 工具类允许你控制元素轮廓的样式,例如实线(solid)、虚线(dashed)或点线(dotted)。轮廓绘制在元素边框的外部,并且至关重要的是,它们不占用布局空间,这使它们成为焦点指示器的理想选择。

理解两者之间的区别至关重要:

  • border:是盒模型(box model)的一部分。添加边框会增加元素的总大小,并可能导致布局偏移。
  • outline:在布局之上渲染。添加轮廓不会影响元素的大小或周围元素的位置。
类名CSS 属性
outline-noneoutline: 2px solid transparent; outline-offset: 2px;
outlineoutline-style: solid; (assumes outline-width and outline-color are also set)
outline-dashedoutline-style: dashed;
outline-dottedoutline-style: dotted;
outline-doubleoutline-style: double;

轮廓(outline)的主要用例是为交互元素提供清晰、可见的焦点指示器,这是 Web 无障碍性(a11y)的基石。让我们为一组输入框设置样式,使其使用轮廓工具类拥有清晰且吸引人的焦点状态。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/dist/output.css" rel="stylesheet">
<title>无障碍轮廓样式</title>
</head>
<body class="bg-slate-100 flex items-center justify-center min-h-screen">
<form class="bg-white p-8 rounded-lg shadow-lg w-full max-w-md">
<h1 class="text-2xl font-bold mb-6 text-slate-800">创建您的账户</h1>
<div class="mb-4">
<label for="email" class="block text-slate-700 text-sm font-bold mb-2">电子邮件地址</label>
<input id="email" type="email"
class="w-full px-3 py-2 border border-slate-300 rounded-md
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="you@example.com">
</div>
<div class="mb-6">
<label for="password" class="block text-slate-700 text-sm font-bold mb-2">密码</label>
<input id="password" type="password"
class="w-full px-3 py-2 border border-slate-300 rounded-md
focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-pink-500"
placeholder="••••••••">
</div>
<button type="submit"
class="w-full bg-blue-600 text-white font-bold py-2 px-4 rounded-md
hover:bg-blue-700
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
注册
</button>
</form>
<div class="absolute bottom-4 right-4 bg-green-100 border-l-4 border-green-500 text-green-800 p-4 rounded-md shadow-md">
<p class="font-bold">无障碍最佳实践:`focus-visible`</p>
<p>考虑使用 `focus-visible` 变体而不是 `focus`。这只在用户通过键盘(例如,使用 Tab 键)导航时应用焦点样式,而不是在鼠标点击时,为鼠标用户提供更整洁的体验,同时保持无障碍性。</p>
<p class="mt-2 font-mono text-sm">示例:`focus-visible:ring-2`</p>
</div>
</body>
</html>