helion3 February 2016

Equal-width form labels with arbitrary horizontal rules

I have a horizontal label: <input> style form. Labels need to be equal widths, but dynamic - based on the longest label in the form. Normally, I'd solve this with a series of display: table/row/cell elements, but we also need a horizontal rule separating some of these rows.

display: table does not play well with non-row/cell elements inside it.

The core form structure:

<form>
    <div class="group">
      <span>test</span>
      <div class="field">
        <input type="text">
      </div>
    </div>
    <hr>
    <div class="group">
      <span>test long</span>
      <div class="field">
        <input type="text">
      </div>
    </div>
    <div class="group">
      <span>test</span>
      <div class="field">
        <input type="text">
      </div>
    </div>
  </form>

The CSS:

* { box-sizing: border-box; }
html, body { width: 100%; }

form {
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border: 1px solid red;
}

.group {
  display: table-row;
}

span {
  display: table-cell;
  background: #ddd;
  padding: 0 10px 0 0;
  white-space: nowrap;
  width: 1px;
}

input, hr {
  width: 100%;
}

The label widths work as I'd expect, yet the hr cannot fill 100% width. I can get the right width by making it position: absolute, but then I lose the spacing between the rows. I can make it a display: table-row but no longer have control over the spacing.

JSBin

Answers


xpy February 2016

This was a funny one.

I don't know how much strict you are about the design but here is an ok solution.

hr{
  display:table-cell;
  padding:10px 0;
  border:none;
  box-sizing:content-box;
  background:black;
  height:1px;
  background-clip:content-box;
}

using table-cell on the hr you can expand it to full width, with a little trick on the padding and background-clip you can have a simple horizontal line. If you want to take it further you can add an image as a background and use repeat-x to expand it in full width.

Post Status

Asked in February 2016
Viewed 2,656 times
Voted 4
Answered 1 times

Search




Leave an answer