Vertically align `label` and `input`, without messing up the line-height?

So this is something that's been bothering me lately. If I have a label and an input (no matter what type), how can I vertically align them when there's one row, but also make sure that if the label is on multiple lines, that it's actually just the first row that aligns? Let's say the label content would be: "Label Second line" It would look like in the screenshot, but "Second line" would just go underneath. This mean I can't use flex/grid and use align-items: center. Nor can I change the line-height to equal the checkbox, because I might have another input type that has a different height. I've been using padding-block-start for now, but that is also different, depending on the input type's height. Is there a more dynamic way I can approach this? Example: https://codepen.io/erikblomqvist/pen/mdoGGKm
No description
4 Replies
MarkBoots
MarkBoots10mo ago
yea, not that easy i think. a (not so elegant) way could be
input[type=text]{
height: 40px;
}
label:has(+ input[type="text"])::first-line {
line-height: 40px;
}
input[type=checkbox] {
margin: 0;
height: 24px;
}
label:has(+ input[type="checkbox"])::first-line {
line-height: 24px;
}
input[type=text]{
height: 40px;
}
label:has(+ input[type="text"])::first-line {
line-height: 40px;
}
input[type=checkbox] {
margin: 0;
height: 24px;
}
label:has(+ input[type="checkbox"])::first-line {
line-height: 24px;
}
but that will make the lineheight inconsistent
somrigostsås 🧀
somrigostsås 🧀OP10mo ago
It's interesting approach, though! But I guess using a CSS variable for both height and line-height could be used.
somrigostsås 🧀
somrigostsås 🧀OP10mo ago
This will be the output, though.
No description
somrigostsås 🧀
somrigostsås 🧀OP10mo ago
I think this is a fairly reasonable approach. Then you might have other input, say a toggle switch, with a height of 32px, and it still works.
.group {
display: flex;
align-items: start;
justify-content: space-between;

margin-block-end: 1rem;

--height: 40px;

&:has(input[type="checkbox"]) {
--height: 24px;
}
}

label {
--line-height: 24px;

padding-block-start: calc((var(--height) - var(--line-height)) / 2);

line-height: var(--line-height);
}

input {
height: var(--height);

&[type=checkbox] {
margin: 0;
}
}
.group {
display: flex;
align-items: start;
justify-content: space-between;

margin-block-end: 1rem;

--height: 40px;

&:has(input[type="checkbox"]) {
--height: 24px;
}
}

label {
--line-height: 24px;

padding-block-start: calc((var(--height) - var(--line-height)) / 2);

line-height: var(--line-height);
}

input {
height: var(--height);

&[type=checkbox] {
margin: 0;
}
}
Want results from more Discord servers?
Add your server