skip to Main Content

The height and width of a parent div containig a child textarea can be made exactly equal with the following CSS: https://jsfiddle.net/BwVQZ/7/

<div>
    <textarea></textarea>
</div>
div{
    height: 200px;
    width: 300px;
    background: red;
}
textarea{
    height: 100%;
    width: 100%;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}

The problem with the above approach is that I have hardcoded the height and width of the div, which I cannot do for my real use-case.

If I don’t hardcode the height and width, then the div gets a slightly bigger height that the textarea: https://jsfiddle.net/731ce2u4/

<div>
    <textarea></textarea>
</div>
div{
    background: red;
}
textarea{
    height: 100%;
    width: 100%;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}

Does anyone know how to make the height and width of the div and textarea equal, without hardcoding any heights or widths?

2

Answers


  1. You may change CSS a little bit, like:

    div{
        
        background: red;
        display: grid;
    }
    textarea{
        height: 100%;
        width: 100%;
        -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
        -moz-box-sizing: border-box;    /* Firefox, other Gecko */
        box-sizing: border-box;         /* Opera/IE 8+ */
    }
    <div>
        <textarea></textarea>
    </div>

    Now you may adjust textarea as per your requirement.

    Login or Signup to reply.
  2. By default display: block; is set.

    Use display: flex; in parent div container.

    div{
        background: red;
        display:flex;
    }
    textarea{
      height:100%;
      width:100%;
      -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
      -moz-box-sizing: border-box;    /* Firefox, other Gecko */
      box-sizing: border-box;         /* Opera/IE 8+ */
    }
    <div>
        <textarea></textarea>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search