How to force free CSS resize on input element when its width is specified?

后端 未结 4 1330
刺人心
刺人心 2021-02-05 15:30

I have simple problem - text input element which has specified 2 CSS attributes, see code below:



        
相关标签:
4条回答
  • 2021-02-05 15:59

    Everything I read online (see below) indicates that the resize property only works on block level elements that do not have overflow: visible set and on textarea elements. It does not even technically work for input elements (which are neither, and even if set to display: block I could not get the resize to be recognized by Firefox).

    Links: https://developer.mozilla.org/en/CSS/resize and http://www.css3.info/preview/resize/ and http://www.w3.org/TR/css3-ui/#resize

    0 讨论(0)
  • 2021-02-05 16:01

    This is pretty close to workable. You need to set size="1" as an attribute on the <input> to resize really small. The resize is controlled by input:active which overrides the base class with width: auto;. input:focus prevents it from shrinking when you tab into it to type.

    Potential issues: input:focus forces the <input> to a specific min-size, which might be larger than what it's been resized to. You could min-width: 100% to make this a "feature" instead of an issue, giving the user more space to type. If the <input> has focus, resize is still limited by min-width, but resize is usually done post-focus (and also, mostly used to make something larger).

    Demo: http://jsfiddle.net/ThinkingStiff/jNnCW/

    HTML (with styles inline as you requested):

    <input id="text" type="text" size="1"/>
    <style>
        input {
            resize: horizontal;
            width: 200px;
        }
    
        input:active {
            width: auto;   
        }
    
        input:focus {
            min-width: 200px;
        }
    </style>    
    
    0 讨论(0)
  • 2021-02-05 16:03

    Here is an example of using div with flexbox & contenteditable=true instead of input. Only CSS + HTML. I found it useful if no tag 'form' required.

    #flex {
      display: flex;
      display: -webkit-flex;
      line-height: 30px;
    }
    #inner {
        padding: 0 20px;
        min-width: 100px;
        height:30px;
        line-height:30px;
        outline:none;
        background-color: #dfd4d7;
    }
    <div id="flex">Type some text here:
    <div id="inner" contenteditable="true" spellcheck="false"><div>
    </div>

    0 讨论(0)
  • 2021-02-05 16:03

    The simple way to make an input resize freely is to set it to it to have width: 100%, and then place it inside an inline-block container with a min-width (min-width sets the default width for the input). Resize the container to resize the input.

    See: http://jsfiddle.net/Wexcode/TvZAr/

    0 讨论(0)
提交回复
热议问题