如何固定Grid布局外Cookie同意弹窗的位置且不占用布局空间
解决方案
你当前的cookie consent元素定位异常的核心原因是:绝对定位的参考上下文为全局视口,而你的核心内容容器.container是居中自适应的,窗口宽度变化时,视口右边缘与容器右边缘的间距会动态变化,写死的right: 150px自然无法固定位置。
你只需要做3处调整即可解决问题,完全不需要改动原有Grid布局逻辑:
- 给
.container新增position: relative属性,将其设置为绝对定位的参考上下文 - 将
.cookie-consent元素从body的直接子元素,挪到.container内部作为第一个子元素 - 根据你的实际需求调整
.cookie-consent的right值,改为相对于.container右边缘的距离即可
修改后的代码示例
调整CSS
.container { display: grid; height: 100vh; margin: auto; max-width: 80%; position: relative; /* 新增这一行 */ grid-template-columns: 1fr 1fr 1fr 1fr; grid-template-rows: 0.2fr 1.2fr 1.8fr 0.3fr; grid-template-areas: "nav nav nav nav" "component1 component1 component1 component1" "component2 component2 component2 component2" "footer footer footer footer"; grid-gap: 0.5rem; font-weight: 800; text-transform: uppercase; text-align: center; } /* 按需调整right值,比如这里设置为距离容器右边缘30px */ .cookie-consent { background: red; width: 200px; height: 100px; position: absolute; bottom: 30px; right: 30px; z-index: 20; }
调整HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="./style.css" /> <title>Document</title> </head> <body> <div class="container"> <div class="cookie-consent"></div> <!-- 移到容器内部 --> <nav>Navbar</nav> <div id="component1">component1</div> <div id="component2">component2</div> <footer>Footer</footer> </div> </body> </html>
调整完成后,cookie consent元素始终相对于你的核心内容容器定位,无论页面宽高如何变化,位置都会保持固定,同时因为是绝对定位脱离文档流,完全不会占用Grid布局的空间,不会影响原有布局逻辑。
内容的提问来源于stack exchange,提问作者herbert mühlex
相关产品推荐
相关产品推荐

