创建<textarea>填充剩余高度</textarea>

时间:2013-08-27 06:27:23

标签: css

我从this question了解到如何使HTML元素填充容器的剩余高度。但它似乎与<textarea>无关。这个小提琴比较了display: table-row<textarea><div>的影响:

http://jsfiddle.net/b4Tt8/2/

为什么不同,以及如何才能在textarea上获得适当的效果?

3 个答案:

答案 0 :(得分:10)

您可以使用flexbox根据其父级设置textarea高度。

<强> HTML

<div class="container">
  <div class="btn-wrapper">
    <button>X</button>
  </div>
  <textarea></textarea>
</div>

<强> CSS

.container {
  height: 220px;
  width: 220px;
  background-color: pink;
  display: flex;
  flex-direction: column; 
 } 

.container textarea {
  box-sizing: border-box; /* fit parent width */
  height: 100%;
}

jsFiddle

答案 1 :(得分:1)

为什么使用display: table-row;声明?没有必要这样做。删除display: table-row;声明,向您的textarea选择器添加box-sizing: border-box;声明,然后全部设置:

.container
{
    height: 220px;
    width: 220px;
    background-color: pink; 
}

.container > textarea
{
    width: 100%;
    height: 100%;
    background-color: cyan;
    box-sizing: border-box;
}

.container > div
{
    width: 100%;
    height: 100%;
    background-color: cyan;
}

Fiddle

编辑:

上面的CSS使文本区域溢出其父div。

以下是更新的答案:

HTML

<div class="container">
    <div class="button-wrapper">
        <button>X</button>
    </div>
    <div class="textarea-wrapper">
        <textarea></textarea>
    </div>
</div>

CSS 2

.container {
    height: 220px;
    width: 220px;
    background-color: pink;
    position: absolute;
}
.container textarea {
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 0, 0.5);
    box-sizing: border-box;
}
.container > div {
    background-color: cyan;
}
.container .button-wrapper {
    background-color: yellow;
    height: 26px;
}
.container .textarea-wrapper {
    background-color: green;
    position: absolute;
    top: 26px;
    width: 100%;
    bottom: 0;
}

CSS 3(使用计算功能)

.container {
    height: 220px;
    width: 220px;
    background-color: pink;
}
.container textarea {
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 0, 0.5);
    box-sizing: border-box;
}
.container > div {
    background-color: cyan;
}
.container .button-wrapper {
    background-color: yellow;
    height: 26px;
}
.container .textarea-wrapper {
    background-color: green;
    height: calc(100% - 26px);
}

以下是显示两种解决方案的小提琴:

CSS 2

CSS 3

答案 2 :(得分:0)

如果您将固定高度设置为button,那么您可以使用定位并执行以下操作:

HTML :( 删除了br标记

<div class="container">
    <button>X</button>
    <textarea></textarea>
</div>
<div class="container">
    <button>X</button>
    <div>Text</div>
</div>

CSS

.container {
    height: 220px;
    width: 220px;
    background-color: pink;
    display: table;
}
.container > button {
    display: table-row;
}
.container > textarea, .container > div {
    display: table-row;
    border: none;  /* if you keep border then textarea will go out of the parent element */
    height: 200px; /* hardcoded */
    padding: 0px;  /* removing padding for chrome */
    width: 100%;
    background-color: cyan;
}

<强> Working Fiddle

相关问题