导航栏与侧边栏CSS hover、after属性异常及响应式grid布局问题求助
问题1:导航栏hover动画修复
你当前的nav a::after没有设置初始宽度和左对齐属性,导致伪元素位置偏移。修改对应CSS即可:
nav { /* 原代码写了align-items但没设置flex布局,补上 */ display: flex; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); background: linear-gradient(#ffffff, #f5f5f5); grid-area: nav; margin: 0; align-items: center; padding: 1em 0; } nav a::after { content:''; position: absolute; display: block; height: 0.4em; background-color: rgb(255, 160, 0); bottom: -1em; /* 新增以下两行 */ width: 0; left: 0; transition: all ease-in-out 250ms; } nav a:hover::after { /* 现在位置对齐了,按需求设置宽度即可,不需要超过100% */ width: 60%; }
问题2:grid布局响应式+等高+footer固定显示
首先你原来的媒体查询里类名写错了,写的.container实际布局类是.layout,导致响应式规则完全没生效。修改如下:
.layout { display: grid; /* 把固定高度改成最小高度,内容超出时自动撑开 */ min-height: 100vh; grid-template-columns: 1fr 1fr 5fr 1fr; /* 行高改成自适应,中间区域自动占剩余高度,footer始终贴底 */ grid-template-rows: auto auto 1fr auto; grid-template-areas: "title title title title" "nav nav nav sidebar" "main main main sidebar" "footer footer footer footer"; grid-gap: 10px; padding: 10px; } /* 侧边栏盒子不要写死宽度,自适应父容器 */ .box { text-align: center; width: 100%; box-sizing: border-box; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); background: linear-gradient(#ffffff, #f5f5f5); padding: 20px; margin: 0 0 10px 0; } @media only screen and (max-width:550px) { /* 把.container改成.layout */ .layout { grid-template-columns: 1fr; grid-template-rows: auto auto 1fr auto auto; grid-template-areas: "title" "nav" "main" "sidebar" "footer"; } }
grid布局默认同一行的单元格高度自动等高,改完后main和sidebar高度会自动保持一致,footer始终在页面最底部可见。
问题3:侧边栏hover左侧竖线动画
新增以下CSS即可,和导航栏动画逻辑一致,仅把底部横线替换为左侧竖线:
.box_content li a { position: relative; } /* 前两个侧边栏的hover效果 */ .box:nth-child(-n+2) .box_content a::before { content: ''; position: absolute; left: -10px; top: 0; height: 100%; width: 0; background-color: rgb(255, 160, 0); transition: all ease-in-out 250ms; } .box:nth-child(-n+2) .box_content a:hover::before { width: 4px; }
问题4:第三个侧边栏盒子a标签单独样式
用nth-child选择器选中第三个盒子,优先级足够高可以覆盖全局a样式:
/* 第三个盒子的a标签样式 */ .box:nth-child(3) .box_content a, .box:nth-child(3) .box_content a:hover { color: #000 !important; text-decoration: none !important; } /* 隐藏第三个盒子的hover竖线动画 */ .box:nth-child(3) .box_content a::before { display: none !important; }
其他代码问题补充
- DOCTYPE声明写错了,正确写法是
<!DOCTYPE html>不是<!DOCTYPE html5> - 第三个侧边栏的
ul下直接放了a标签,不符合HTML规范,建议给每个a标签外层套<li>
内容的提问来源于stack exchange,提问作者user14865888
相关产品推荐
相关产品推荐

