'Boostrap: Input Labels on border
Searched quite a lot, couldn't find anything - am I really the only one?
How do I turn
<div class="form-group">
<label for="input1" >Username</label>
<input type="text" class="form-control" id="input1" value="boern">
</div>
Into this (where the label is inline / on the border / stroke):
Aren't there any prefined boostrap scss
tricks or classes that I can used without messing myself with the css like so (the less CSS I write, the better):
<div class="form-group">
<label for="input1" style="margin-left: 12px; margin-left: 15px;
margin-top: -12px; position: absolute;
background-color: white; border: 2px solid white;">
Username
</label>
<input type="text" style="height: 3.3rem;" class="form-control" id="input1" value="boern">
</div>
Thanks!
Solution 1:[1]
If you are using bootstrap 4 (which I assume) you can achieve "labels on border" with no dirty inline / custom CSS by using a mix of spacing classes -> https://getbootstrap.com/docs/4.5/utilities/spacing/ :
<div class="form-group">
<label for="input1" class="col-sm-2">
<span class="h6 small bg-white text-muted pt-1 pl-2 pr-2">Username</span>
</label>
<input type="text" class="form-control mt-n3" id="input1" value="boern">
</div>
The most important here is the negative .mt-n3
margin. It looks like this
demo -> https://jsfiddle.net/nksz9g5e/
Perhaps you want to customize the label font size, .h6 .small
is the smallest "native" size I can think of. And perhaps the labels right gutter should be adjusted.
Solution 2:[2]
For Bootstrap 5 I manage to implement it as well like so:
<form class="card card-body">
<div class="row">
<div class="col px-1 mb-2">
<label for="input1" class="ms-2 position-absolute" style="margin-top: -0.25rem !important">
<span class="h6 small bg-white text-muted px-1">Username</span>
</label>
<input type="text" class="form-control mt-2" id="input1">
</div>
<div class="col px-1 mb-2">
<label for="input2" class="ms-2 position-absolute" style="margin-top: -0.25rem !important">
<span class="h6 small bg-white text-muted px-1">Password</span>
</label>
<input type="password" class="form-control mt-2" id="input2">
</div>
</div>
</form>
If you have enabled negative margins in your SASS you can omit the style
attribute in your label
tags and just add .mt-n1
to it's class.
Demonstration: https://jsfiddle.net/t4cwnxbh/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | whocares4400 |