talena6 talena6 - 3 months ago 7
HTML Question

How can I add a padding before and after a label that overlaps the top border of an input field?

I am trying to create input fields that look like this 1

which is easy enough because I can add a white background to the label with some padding. The problem is when the field appears on a non-white background like this

2

Is there any way to accomplish this with a transparent background on the label?

https://jsfiddle.net/jgu61qaq/

<div class="floating-label bg-white">
<label>Label</label>
<input type="text" value="Something">
</div>

<div class="floating-label bg-gray">
<label>Label</label>
<input type="text" value="Something">
</div>

<style>
.floating-label {
padding: 20px;
position: relative;
font-family: Arial, sans-serif;
}

.bg-white {
background: #fff;
}

.bg-gray {
background: #eee;
}

input {
padding: 5px 10px;
font-size: 14px;
}

label {
font-size: 11px;
position: absolute;
top: 15px;
left: 25px;
background: #fff;
padding: 0 5px;
}
</style>

Answer

Maybe something like this?:

label {
  position: relative;
  top: -16px;
  left: 46px;
  z-index: 0;
}
label:before {
  z-index: -1;
  content: '';
  display: block;
  width: 100%;
  height: 50%;
  background-color: #fff;
  position: absolute;
  top: 50%;
  margin-top: -1px;
}

https://jsfiddle.net/jgu61qaq/3/

I used :before selector to create a white 50% height of label element to hide the border

Comments