1

I have a form with fieldsets, and would like to keep the border, but would like the border to be shown between some text legends. I can't get the legend to have a transparent background to let the border through (to be blocked by some text elements).

legend {
    display:flex;
    justify-content:space-between;
    width: 100%;
    background-color: transparent;
}

legend div {
    background-color: white;
    margin-left:0.5em;
    margin-right:0.5em;
}
<form>
  <fieldset>
    <legend><div>Form Item</div><div>(extra 1)</div></legend>
    <label>Input:</label><input></input>
  </fieldset>
</form>

1
  • background: linear-gradient(black ,black) center / 100% 1px no-repeat; on the <legend>
    – user7148391
    Commented May 24, 2021 at 20:41

2 Answers 2

1

Extra div hack. If there is a way to do this without the extra div, that would be great.

I guess if I force the fieldset border (chrome's default border is 2px groove threedface), it works ok.

fieldset {
    border: 1px solid black;
}

legend {
    display:flex;
    justify-content:space-between;
    width: 100%;
    position: relative;
}
legend div {
    background-color: white;
    margin-left:0.5em;
    margin-right:0.5em;
}
legend div.line {
    flex: 1 1 auto;
    background-color: transparent;
}

legend div.line:before {
    position: absolute;
    z-index: -1;
    content: '';
    left: 0px;
    right: 0px;
    top: 50%;
    border-top: 1px solid black;
}
<form>
  <fieldset>
    <legend><div>Form Item</div><div class="line"></div><div>(extra 1)</div></legend>
    <label>Input:</label><input></input>
  </fieldset>
</form>

1
  • Of course border-top is off by 1px in firefox(top: calc(50% - 1px); or margin-top: -1px; works)
    – Stephen
    Commented May 24, 2021 at 20:34
0

background can approximate this without an extra div. You simply need to find the correct color:

fieldset {
  border: 1px solid black;
}

legend {
  display: flex;
  justify-content: space-between;
  width: 100%;
  background: linear-gradient(black 0 0)center/100% 1px no-repeat;
}

legend div {
  background-color: white;
  padding:0 0.5em;
}
<form>
  <fieldset>
    <legend>
      <div>Form Item</div>
      <div>(extra 1)</div>
    </legend>
    <label>Input:</label><input>
  </fieldset>
</form>

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