How to include a title in a box as a <legend> is within a <fieldset> using Tailwind CSS

Viewed 211

With or without Tailwind CSS, an HTML <fieldset> can be boxed in with a <legend> inside the box line. How can this be done w/o using <fieldset> when the same look is desired but when it is not part of a <form>, aside from just dropping the <form> using Tailwind CSS.

Such as, in this example, using a <div> & <h2>.

<!DOCTYPE html>
<html lang='en-US'>
<head>
<meta charset='UTF-8' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<link href='tailwind.css' rel='stylesheet'>
</head>
<body class='p-3'>
<fieldset class='p-3 border border-black'>
  <legend>A Legend Title</legend>
  Blah blah. Blah blah.
</fieldset>
<div class='p-3 border border-black'>
  <h2>A Heading</h2>
  Blah blah. Blah blah.
</div>
</body>
</html>

  vs  with

1 Answers

You may be looking for an effect like this:

<div class='p-3 border border-black relative mt-12'>
    <h2 class="absolute -top-1/2 translate-y-1/2 bg-white">A Heading</h2>
    Blah blah. Blah blah.
</div>

Absolutely positioning the heading to the relative parent and giving it a white (or whatever color your bg is) background. However, if your background is not a single solid color this can cause problems.

Here's a play example https://play.tailwindcss.com/OG3rmf1K8e

Edit:

I came up with a somewhat ridiculous workaround using flex and only Tailwind classes. It gets rid of the issue of the other solution since the heading element no longer has a background.

It uses an absolutely positioned flex container to simulate a broken top border and ends up looking very similar to the fieldset legend.

Here's a play example of it: https://play.tailwindcss.com/oBVHLKRDVl

<div class='p-3 pt-6 border border-t-0 border-black mt-12 relative'>
  <div class="flex absolute w-full -top-3 left-0 right-0 items-center">
    <span class="block border-t border-black flex-0 w-3" ></span>
    <h2>A Heading</h2>
    <span class="block border-t border-black flex-1" ></span>
  </div>
  Blah blah. Blah blah.
</div>

Edit 2:

It's also really simple to center the heading with this solution, just remove the fixed width of the first span and give it flex-1.

Like this: https://play.tailwindcss.com/2Rwa9bQKeU

Or if you want it flipped and heading near the end, just switch the fixed width to the second span and give the first flex-1.

Like this: https://play.tailwindcss.com/JJtPV0gca2

Related