點燈坊

失くすものさえない今が強くなるチャンスよ

Using before to Create a Fun Background for an Image

Sam Xiao's Avatar 2022-01-26

With new before and after modifiers, we can create lots of fun effects to decorate the element.

Version

TailwindCSS 3.0

before

rotate000

Let’s try and create a fun background for an image.

<!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='flex items-center justify-center max-w-prose min-h-screen mx-auto'>
    <div class='before:block before:absolute before:-inset-1 before:-rotate-6 before:bg-teal-500 relative'>
      <img class='relative border-4 border-white' src="https://picsum.photos/300/200/?random=10">
    </div>
  </div>
</body>

Line 10

<div class='flex items-center justify-center max-w-prose min-h-screen mx-auto'>
  • flex : make parent element as Flex box and child element as Flex item
  • items-center : all Flex items are vertical center
  • justify-center : all Flex items are horizontal center
  • max-w-prose : set the width of max-width
  • min-h-screen : set height of max-height
  • mx-auto : make Flex box horizontal center

Line 11

<div class='relative before:absolute before:-inset-1 before:-rotate-6 before:bg-teal-500'>
  • before:absolute : create a pseudo element with absolute position
  • before:-inset-1 : create a pseudo element with top/right/bottom/left position
  • before:-rotate-6 : create a pseudo element with rotating
  • before:g-teal-500 : create a pseudo element with background
  • relative : set the element as relative position for absolute

Line 12

<img class='relative border-4 border-white' src="https://picsum.photos/300/200/?random=10">
  • relative : prevent the element from overlaping by the pseudo element
  • border-4 : set the border width
  • border-white : set the border color

Conclusion

  • before + absolute + relative is a common pattern for decorating the element

Reference

Chris Bongers, TailwindCSS Pseudo-elements