Textarea padding inconsistency in Firefox and Chrome

前端 未结 3 2015
青春惊慌失措
青春惊慌失措 2021-02-18 15:18

I have a padding on my textarea element and I would like the content to remain padded as you scroll within the textarea. It is working as expected in Firefox but not in Chrome.

3条回答
  •  臣服心动
    2021-02-18 15:43

    You could do something like this, it's not very flexible (fixed width), but you can expand on it. It fixes the issue in Chrome and doesn't break Firefox. It uses pseudo-elements on #container, which work in IE8+

    textarea {
        width: 250px;
        height: 160px;
        padding: 15px;
        font-family: Arial;
        font-size: 12px;
        line-height: 18px;
        border: 1px solid #CCCCCC;
        overflow: auto;
        resize: none;
        display: block;
    }
    #container:before, #container:after {
        display: block;
        height: 15px;
        background-color: #FFF;
        position: absolute;
        left: 1px;
        width: 225px;
        content:'';
    }
    #container:before {
        top: 1px;
    }
    #container:after {
        bottom: 6px;
    }
    

    Here's a jsFiddle.

    Update: Added display: block to textarea to fix IE positioning issue.

    Update 2: Alternative solution which takes its width from the #container div and for which you'd need to set the right value based on the width of the scrollbar of the browser, the 17px value is ok in Chrome at the moment. A pro with this solution is that you can set the width of the textarea to anything by changing the width of the #container, and the pseudo-elements will scale accordingly. jsFiddle.

    #container {
        width: 260px;
        margin: 20px auto;
        position: relative;
    }
    textarea {
        width: 100%;
        height: 160px;
        padding: 15px;
        font-family: Arial;
        font-size: 12px;
        line-height: 18px;
        border: 1px solid #CCCCCC;
        overflow: auto;
        resize: none;
        display: block;
    }
    #container:before, #container:after {
        display: block;
        height: 15px;
        background-color: #FFF;
        position: absolute;
        left: 1px;
        right: 17px;
        content:'';
    }
    #container:before {
        top: 1px;
    }
    #container:after {
        bottom: 1px;
    }
    

提交回复
热议问题