點燈坊

うまく使いさえすれば、時間はいつも十分にある

Using before to Decorate the Element

Sam Xiao's Avatar 2022-01-25

We can use before modifier to add a pseudo element on the fly and apply utility.

Version

TailwindCSS 3.0

before

before000

TailwindCSS is a real element on HTML, whereas Awesome is a pseudo element created by before modifier.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body>
  <div class="before:content-['Awesome'] before:text-red-500 before:mr-1">
    TailwindCSS
  </div>
</body>

Line 10

<div class="before:content-['Awesome'] before:text-red-500 before:mr-1">
  TailwindCSS
</div>
  • before:content-['Awesome'] : assign String on before modifier, which sets the content of the pseudo element
  • before:text-red-500 : apply text-red-500 utility on before modifier, which sets the text color of the pseudo element
  • before:mr-1 : apply mr-1 utility on before modifier, which sets the right margin of the pseudo element

inline-block

before001

The pseudo element created by before modifier is inline-block. We have to set it to block to occupy a new line.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body>
  <div class="before:content-['Awesome'] before:text-red-500 before:block">
    TailwindCSS
  </div>
</body>

Line 10

<div class="before:content-['Awesome'] before:text-red-500 before:block">
  TailwindCSS
</div>
  • before:content-['Awesome'] : assign String on before modifier, which sets the content of the pseudo element
  • before:text-red-500 : apply text-red-500 utility on before modifier, which sets the text color of the pseudo element
  • before:block : apply block utility on before modifier, which sets the element as a block-level element

Conclusion

  • By using before modifier, we can decorate the element by creating a pseudo element using utilities

Reference

TailwindCSS, Before and after