纯CSS响应式导航栏问题:大尺寸下内容显示为行内元素
解决纯CSS响应式导航栏下方内容布局异常问题
我在实现纯CSS响应式导航栏,设置768px及以下显示汉堡菜单。导航栏功能正常,但视口尺寸大于768px时,导航栏下方的内容(如H1标签)显示为行内元素,没有正常换行。尝试用CSS网格分离元素,没解决问题,相关代码如下:
CSS代码
.header { width: 100%; z-index: 3; } .header ul { margin: 0; padding: 0; list-style: none; overflow: hidden; } .header li { color: #ffffff; font-weight: 700; font-size: 22px; } .header ul a { display: block; padding: 5px 20px; text-decoration: none; } .header ul a:hover { color: #BDBDBD; } .header .logo { float: left; display: block; font-size: 2em; padding: 10px 20px; } .header .menu { clear: both; max-height: 0; transition: max-height .2s ease-out; } .header .menu-icon { padding: 28px 20px; position: relative; float: right; cursor: pointer; } .header .menu-icon .nav-icon { background: #cccccc; display: block; height: 2px; width: 18px; position: relative; transition: background .2s ease-out; } .header .menu-icon .nav-icon:before { background: #cccccc; content: ""; display: block; height: 100%; width: 100%; position: absolute; transition: all .2s ease-out; top: 5px; } .header .menu-icon .nav-icon:after { background: #cccccc; content: ""; display: block; height: 100%; width: 100%; position: absolute; transition: all .2s ease-out; top: -5px; } .header .menu-btn { display: none; } .header .menu-btn:checked~.menu { max-height: 240px; } .header .menu-btn:checked~.menu-icon .nav-icon { background: transparent; } .header .menu-btn:checked~.menu-icon .nav-icon:before { transform: rotate(-45deg); top: 0; } .header .menu-btn:checked~.menu-icon .nav-icon::after { transform: rotate(45deg); top: 0; } @media (min-width:48em) { .header li { float: left; } .header li a { padding: 20px 30px; } .header .menu { clear: none; float: right; max-height: none; } .header .menu-icon { display: none; } }
HTML代码
<header class="header"> <a href="/" class="logo">LK</a> <input class="menu-btn" type="checkbox" id="menu-btn"> <label class="menu-icon" for="menu-btn"><span class="nav-icon"></span></label> <ul class="menu"> <li><a href="#">Home</a></li> <li><a href="#">Browse</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </header> <div> <h1>This is a heading</h1> </div>
问题原因及解决方案
问题根源
当视口大于768px时,.logo和.menu都使用了float属性,但.header容器没有处理浮动,导致父容器高度塌陷,后续元素会填充到浮动元素旁边的空间,看起来像是行内元素。
解决方法
以下两种方法任选其一即可:
方法一:添加清除浮动的伪元素
给.header添加伪元素来清除内部浮动:
.header::after { content: ""; display: table; clear: both; }
方法二:触发块级格式化上下文(BFC)
修改.header的样式,将其设置为BFC容器,自动包裹内部浮动元素:
.header { width: 100%; z-index: 3; overflow: auto; /* 或使用 display: flow-root; */ }
两种方法都能让.header容器正确包裹浮动元素,后续的H1等内容就会恢复正常的块级元素换行显示。
内容的提问来源于stack exchange,提问作者Anirog
相关产品推荐
相关产品推荐

