I have a row of 3 inputs. One of them has label text placed above its input. I do not want this label text to interfere with the alignment of the inputs. Right now I'm using flexbox in my example. My hack/approach is to use position: absolute;
on my optional label text to remove it from the flex flow so the inputs stay align. However, this creates a bit of spacing inconsistency when wrapping on smaller viewports. I've tried CSS grid as well but had issues where I was stuck writing a media query for every time I needed to wrap, which seemed worse than this. What is the best way to achieve this functionality that allows for a cleaner wrapping?
.container {
display: flex;
flex-wrap: wrap;
align-items: center;
}
.optionalContainer {
position: relative;
/*hack to container optional text*/
padding: 20px 0;
}
.optional {
position: absolute;
top: 0;
margin: 0;
}
<form >
<input required type="text"/>
<div >
<p >Optional:</p>
<input type="text"/>
</div>
<input required type="text"/>
</form>
Example of what I'm shooting for at different viewports:
CodePudding user response:
Here is a solution avoid both positioning and the padding hack using flex with row-gap of the input-height:
:root {
--input-height: 21.2px;
}
.container {
display: flex;
align-items: end;
flex-wrap: wrap;
row-gap: var(--input-height);
}
<form >
<input required type="text" />
<div>
<div>Optional:</div>
<input type="text" />
</div>
<input required type="text" />
</form>
CodePudding user response:
Here is a another solution which avoid both positioning and the padding hack using grid and a grid-template-columns hack:
:root {
--input-width: 146.867px;
--input-height: 21.2px;
}
.container {
display: grid;
/* wrapping hack from https://stackoverflow.com/a/43664701/1248177 */
grid-template-columns: repeat(auto-fill, minmax(var(--input-width), 1fr));
row-gap: var(--input-height);
align-items: end;
}
.optionalContainer > input {
box-sizing: border-box;
width: 100%;
}
<form >
<input required type="text" />
<div >
<div >Optional:</div>
<input type="text" />
</div>
<input required type="text" />
</form>