-1

How can i recreate the classic behavior of a form with fieldset and legend

<form>
  <fieldset>
    <legend>
      Text
    </legend>
  </fieldset>
</form>

using a div and a label?

<div>
  <label>
    Text
  </label>
</div>

I need the label to have a transparent background.

How can I recreate it in a custom way? Thanks

1 Answer 1

0

Not a transparent background, most elements already do that by default. It needs a white background and then just move it up to be on top of the line.

div {
  border: 1px solid #000;
  padding: 10px;
}

label {
  background: #FFF;
  padding: 5px;
  position: relative;
  top: -1rem;
}
<div>
  <label>
    Text
  </label>
</div>

3
  • yes, I had arrived at this result with the white background. but I need it to be transparent because the underlying background can vary, for example it can be a background with gradients. that's why I was wondering if it was possible to make it transparent Commented May 3, 2023 at 17:25
  • Ah I see, you should have specified that in your question. I suppose you could maybe hide the top border and then use ::before and ::after pseudo-elements to be positioned and use them to draw each half of that line... but that would be a real hack to do that. Why not just use the <legend> element and use that default behavior? Why reinvent the wheel?
    – Chris Barr
    Commented May 3, 2023 at 17:34
  • Yes, sorry maybe I wasn't clear. anyway i will try to do as you said. I can't use fieldset and legend because I need the label to be above the input field Commented May 3, 2023 at 17:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.