HiveBrain v1.2.0
Get Started
← Back to all entries
patternhtmlMajor

Stylish underline when input is focused, modern browsers only

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
focusedunderlinebrowsersinputstylishwhenonlymodern

Problem

I've got a text input element which is decorated with an underline. The underline goes up half the height of the input on either side of it and turns blue when the input is focused. It's similar to how inputs look on Android devices.

Here's a JSFiddle and some accompanying code.


    
       

//  Start:normalize
*, *:before, *:after {
    box-sizing: border-box;
}

input:focus {
    outline: none 
}
//  End:normalize

.input-underline-wrapper {
    display: inline-block;
    width: 100%;
}

input {
    width: calc(100% - 2px);
    margin-left: 1px;
    padding-bottom: 2px;
}

input[type=text] {
    border: 0;
    cursor: text;
}

.underline {
    background-color: #ebebeb;
    transition: color 0.3s, background 0.3s, border 0.3s, text-shadow 0.3s;
    z-index: 0;
    height: 5px;
    margin-top: -4px;
    width: 100%;
}

input:focus ~ .underline {
    background-color: #4EA6EA;
}


This all works well and good, but it feels a bit verbose. I'm wondering if I've missed something simple here. Is it possible to achieve the same effect using a white box-shadow which covers the upper-half of the input and omit using a wrapper and a second, underlining div? I only need to support the latest version of Google Chrome.

Solution

Using box-shadows on the input can let you have the same underlining effect without any wrapper or unsemantic markup + strip your CSS a lot :



input[type=text] {
height:17px;
border: 0;
width: calc(100% - 2px);
margin-left:1px;
box-shadow: -8px 10px 0px -7px #ebebeb, 8px 10px 0px -7px #ebebeb;
-webkit-transition: box-shadow 0.3s;
transition: box-shadow 0.3s;
}
input[type=text]:focus {
outline: none;
box-shadow: -8px 10px 0px -7px #4EA6EA, 8px 10px 0px -7px #4EA6EA;
}

``



For browser support :

  • box-shadows : IE9+



  • transitions : IE10+



  • calc() : IE9+

Context

StackExchange Code Review Q#62338, answer score: 23

Revisions (0)

No revisions yet.