How to create background grid in Tailwindcss?

There are so many options to drive user attention to the information we want them to see. One of them is using background grid. In this article let's see how we can achieve this using vanilla css and then using tailwindcss.

Fo example this text without grid background look boring right?

Get started now it's free!

With grid background it look more interesting!

Get started now it's free!

There are two ways to create grid background:

  1. Using svg and css
  2. Using css only

Vanilla CSS and SVG

To start with let's create svg graphics for the grid line.

Here's the svg code, or you can download it here: https://ahmadrosid.com/img/grid.svg.

<svg
  xmlns="http://www.w3.org/2000/svg"
  width="20"
  height="20"
  transform="scale(3)"
>
  <rect x="0" y="0" width="100%" height="100%" fill="hsla(0, 0%, 93%, 1)" />
  <path
    d="M 10,-2.55e-7 V 20 Z M -1.1677362e-8,10 H 20 Z"
    stroke-width="0.2"
    stroke="hsla(0, 0%, 89%, 1)"
    fill="none"
  />
</svg>

And here's the css:

.bg-grid {
  display: grid;
  height: 220px;
  width: 100%;
  place-content: center;
  border-radius: 4px;
  border-width: 1px;
  text-align: center;
  background-image: url(https://ahmadrosid.com/img/grid.svg);
  background-size: 40px 40px;
}

Using tailwindcss

Working with css mean we don't want to write unmaintainable css. So we can improve it with tailwindcss and we don't need to use svg anymore. And we can easily change the style for example the grid size or background color dynamicly from inline css.

Background Grid in Tailwindcss

So we can use tailwindcss like this.

<div class="... h-[120px] relative">
  <div
    class="absolute inset-0 -z-10 h-full w-full bg-gray-50 bg-[linear-gradient(to_right,#f0f0f0_1px,transparent_1px),linear-gradient(to_bottom,#f0f0f0_1px,transparent_1px)] bg-[size:40px_40px]"
  ></div>
  <h1 class="text-4xl font-extrabold tracking-tight">
    Background Grid in Tailwindcss
  </h1>
</div>

In this approach we use trick to create grid effect using linear gradient. And then we repeat that pattern to get the grid effect.

<div
  class="bg-[linear-gradient(to_right,#000000_1px,transparent_1px),linear-gradient(to_bottom,#000000_1px,transparent_1px)]"
></div>

And here's what it look like.

Bonus

I found this cool website, if you want to get ready to use background pattern using this approach you can get it for free here https://bg.ibelick.com/.