让div自动适应内容的高度

我们看下面的代码:
<div id="main">
<div id="content"></div>
</div>

  当Content内容多时,即使main设置了高度100%或auto。在不同浏览器下还是不能完好的自动伸展。内容的高度比较高了,但容器main的高度还是不能撑开。

  我们可以通过三种方法来解决这个问题。
  一,增加一个清除浮动,让父容器知道高度。请注意,清除浮动的容器中有一个空格。
<div id="main">
<div id="content"></div>
<div style="font: 0px/0px sans-serif;clear: both;display: block"> </div>
</div>

  二,增加一个容器,在代码中存在,但在视觉中不可见。
<div id="main">
<div id="content"></div>
<div style="height:1px; margin-top:-1px;clear: both;overflow:hidden;"></div>
</div>

  三,增加一个BR并设置样式为clear:both。
<div id="main">
<div id="content"></div>
<br style="clear:both;" />
</div>
 
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Vue 中让高度根据页面内容自动适应,可以使用以下几种方法: 1. 使用 CSS 中的 flex 布局 在父元素中设置 `display: flex;` 并且将子元素的 `flex-grow` 属性设置为 1,这样子元素就会根据父元素的高度自动适应。 ```html <div class="container"> <div class="content">内容区域</div> </div> ``` ```css .container { display: flex; flex-direction: column; height: 100%; } .content { flex-grow: 1; } ``` 2. 使用 Vue 自带的组件 在 Vue 中可以使用 `keep-alive` 组件或者 `transition` 组件来实现高度适应。这两个组件都会动态添加和移除元素,因此可以根据内容自动计算高度。 ```html <template> <div> <keep-alive> <router-view /> </keep-alive> </div> </template> <style> div { height: 100%; } </style> ``` ```html <template> <transition> <div v-if="show">内容区域</div> </transition> </template> <script> export default { data() { return { show: true } } } </script> <style> div { height: 100%; } </style> ``` 3. 使用 JavaScript 动态计算高度 在 Vue 中可以使用 `ref` 来获取元素的引用,然后使用 JavaScript 动态计算高度。 ```html <template> <div ref="container"> <div>内容区域</div> </div> </template> <script> export default { mounted() { this.$nextTick(() => { const container = this.$refs.container container.style.height = `${container.scrollHeight}px` }) } } </script> <style> div { height: 100%; } </style> ``` 以上是三种常见的让高度根据页面内容自动适应的方法,具体选择哪种方法需要根据具体情况来决定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值