【发布时间】:2013-08-29 18:50:43
【问题描述】:
我从this question 学到了如何使 HTML 元素填充容器的剩余高度。但它似乎不适用于<textarea>。这个小提琴比较了display: table-row 对<textarea> 和<div> 的影响:
为什么会有差异,如何在 textarea 上获得适当的效果?
【问题讨论】:
标签: css
我从this question 学到了如何使 HTML 元素填充容器的剩余高度。但它似乎不适用于<textarea>。这个小提琴比较了display: table-row 对<textarea> 和<div> 的影响:
为什么会有差异,如何在 textarea 上获得适当的效果?
【问题讨论】:
标签: css
您可以使用 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%;
}
【讨论】:
为什么要使用display: table-row; 声明?没有必要这样做。删除 display: table-row; 声明,将 box-sizing: border-box; 声明添加到您的 textarea 选择器中,一切就绪:
.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;
}
编辑:
上面的 CSS 使文本区域溢出其父 div。
这是一个更新的答案:
<div class="container">
<div class="button-wrapper">
<button>X</button>
</div>
<div class="textarea-wrapper">
<textarea></textarea>
</div>
</div>
.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;
}
.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);
}
这里是显示两种解决方案的小提琴:
【讨论】:
如果您将固定高度设置为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;
}
【讨论】: