masadeus masadeus - 3 months ago 29
CSS Question

Style form, underline input

I have this form and I want the placeholder and the input to be underlined. The underline should have the width of the input, as one types the underline grows. With Firefox is an easy thing, just applying:

input {
text-decoration: underline;
}


even though I am not sure if there is a way to style the line. Anyways, when it comes to Chrome, well, not that easy anymore!

I have tried some solutions with jQuery from this thread, but they don't work that good (they would only work proper with a monospaced typography). You can check one of these solutions outcommenting the JS in the codepen.

Any suggestions?

Answer

I've come up with two different solutions.

The first solution uses jQuery to dynamically resize the input to match that of an hidden <span> element. That way, it you don't have to guess the "average size" of a character or anything like that.

$("body").keydown(function(e){
  setTimeout(function(){
    if(e.which == 32){
        $("#clone").append("&nbsp;");
    }
      $("#clone").text($('input').val());
    $('input').width($("#clone").width() + 40);
  }, 100);
});

See: https://jsfiddle.net/pz0f5bam/


The second solution is more just CSS. I started by setting the input width to 100% so that you don't have to worry about it's width being too small. Then if you add text-decoration: underline; to the input it looks like it is growing.

I also added styling to the placeholder to make it look like it has a minimum size.

input{
  width: 100%;
  font-size: 40px;
  text-decoration: underline;
  background-color: transparent;
  outline: none;
  border: none;
}

::-webkit-input-placeholder {
    text-decoration: underline;
    color: black;
}

See: https://jsfiddle.net/vrodL180/