html实现输入框高度自适应
情况一:父div中只有一个元素时正常写
做网页的时候为了解决textarea输入时可以随着文本的增加自动调整高度,将父div的heigth设置为auto
情况二:父div中有两个元素且设置了浮动,如果设置父div高度为auto后会出现下图的情况
</div>
<div style="width: 200px;height: 50px;float: right">
<textarea class="textarea"></textarea>
</div>
<div style="clear: both"></div> <------清除浮动
加上清除浮动的标签后,父div并不能随着文本框的高度增加而增加
解决方案
将div设置为可输入状态 contenteditable=“true”,实现类似文本框的效果
全部代码:
<style>
.header{
height: auto;//关键代码,父div的高度自适应,可以跟随子div高度变化
width: 300px;
background-color: #8FCDA0;
padding-top: 20px;
padding-bottom: 20px;
}
.header_left{
float: left;//关键代码,设置子div浮动效果
width: 100px;
height: 50px;
line-height: 50px;
text-align: center;
font-size: 5px;
background-color: #F581B1;
}
.header_right{//可输入div的样式,类似文本框
min-height: 50px;//设置最小高度
height: auto;//高度根据内容自适应
float: right;//关键代码,设置子div浮动效果
width: 198px;
border: 1px solid #4E5465;
background-color: white;
}
.footer{
width: 300px;
height: 100px;
color: white;
margin-top: 20px;
background-color: #4E5465;
}
</style>
<body>
<div class="header">
<div class="header_left">一个div输入框</div>
<div class="header_right" contenteditable="true"></div>
<!--设置为可输入状态-->
<div style="clear: both"></div>
<!--清除浮动-->
</div>
<div class="footer">我是底部的div</div>
</body>
效果:
(底部的div大小没有变化,只是切图时丢失了)