如何实现子div固定在父级div底部,不随父容器滚动移动
问题根源
- HTML结构非法:标签不允许嵌套使用,你现在的代码里多层标签嵌套会导致浏览器DOM解析异常,直接干扰定位规则生效
- 定位逻辑错误:
position: absolute是相对于父元素的内容流定位,父元素设置overflow-y: auto时,absolute定位元素会被识别为普通内容跟随滚动,无法固定在可视区域底部 - 结构未做隔离:可滚动内容和固定页脚没有分层,全部放在了滚动容器内
修复方案
第一步:调整CSS代码
.sub_topics_column { margin-top: 1%; left: 15%; width: 45%; height: 475px; border: 1px solid #8c8c8c; border-radius: 3px; background-color: white; position: relative; /* 外层容器禁止滚动,滚动逻辑移到内部内容区 */ overflow: hidden; } /* 新增可滚动内容区样式 */ .sub_content { /* 高度 = 容器总高度 - 页脚高度,根据实际页脚高度调整差值即可 */ height: calc(100% - 33px); overflow-y: auto; overflow-x: hidden; } .sub_parent { margin: 2% 0 0 2%; width: 95%; height: 100px; display: flex; } .sub_topics_column .sub_footer { bottom: 0; left: 0; height: 33px; width: 100%; display: flex; border: 1px solid #000; position: absolute; /* 加背景避免滚动内容透上来 */ background-color: #fff; }
第二步:调整PHP输出的DOM结构
删除嵌套的标签,拆分可滚动内容区和固定页脚:
echo "<div class='sub_topics_column'> <!-- 可滚动内容区 --> <div class='sub_content'> <a href='post.php?postses_id=$post_id'> <div class='sub_parent'> ... </div> </a> <!-- 其他需要滚动的内容全部放在这个区域内 --> </div> <!-- 固定页脚放在滚动区外 --> <div class='sub_footer'> <div class='comments_footer'> <div onClick='javascript:toggle$subtopic_id(event)' class='newsfeedPostOptions'> Comments($comments) </div> <div class='post_comment' id='toggleComment$subtopic_id' style='display:none;'> <iframe src='comment_frame.php?subtopic_id=$subtopic_id' id='comment_iframe' frameborder='0'></iframe> </div> </div> <form method='post' target='frame'> <div class='save_footer'> <input style='display: none' type='text' name='current_user' value='$userLoggedIn' /> <input style='display: none' type='text' name='post_id' value='$subtopic_id' /> $bookmark_ele </div> </form> <div class='report_footer' onclick='optionsFunction()'> <button role='button'>Report</button> </div> <div class='votes_footer' onClick='javascript:toggle$subtopic_id(event)'> <iframe id='iframe1' width='49' height='30' scrolling='no' src='likes.php?post_id=$post_id' ></iframe> </div> </div> </div><br><br>";
内容的提问来源于stack exchange,提问作者sir toby
相关产品推荐
相关产品推荐

