为何设置属性后Navbar仍无法固定在顶部?(Tailwind CSS)
问题根源
- 导航栏同时使用了
absolute和fixed定位类,二者属性冲突,fixed的固定效果被absolute覆盖 - body设置了
h-screen,页面高度被锁死在视口高度,超出内容无法正常滚动,影响固定导航的表现 - 固定导航栏会遮挡页面顶部内容,未预留足够的内边距
修复步骤
- 删除nav标签中的
absolute类,仅保留fixed top-0 z-10实现顶部固定 - 移除body上的
h-screen类,让页面高度随内容自动延伸,保证滚动正常 - 给body添加
pt-16(与导航栏的h-16高度匹配),避免内容被导航栏遮挡 - 可删除页面末尾空的
h-screen w-screendiv,该元素无实际作用且占用高度
修改后的完整代码
<!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"> <title>Text1</title> <link rel="stylesheet" href="style.css"> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-[url('https://hips.hearstapps.com/hmg-prod/images/cute-cat-photos-1593441022.jpg?crop=1.00xw:0.753xh;0,0.153xh&resize=1200:*')] bg-center bg-cover bg-no-repeat backdrop-blur pt-16"> <nav class="flex fixed top-0 z-10 justify-between h-16 w-full bg-gray-800 px-5 items-center font-semibold text-xl text-white font-sans border-b-4 border-black"> <div class="w-1/6"> <a href="#" class="font-bold">Text1</a> </div> <div class="space-x-10 "> <a href="#" class="p-4 hover:bg-gray-600 active:bg-gray-400">Text1</a> <a href="#" class="p-4 hover:bg-gray-600 active:bg-gray-400">Text1</a> <a href="#" class="p-4 hover:bg-gray-600 active:bg-gray-400">Text1</a> <a href="#" class="p-4 hover:bg-gray-600 active:bg-gray-400">Text1</a> </div> <div class="w-1/6"> </div> </nav> <div class="flex z-10 justify-center items-center m-80 pt-5 justify-center font-bold text-white font-sans text-6xl border-4 bg-gray-800 rounded-full border-black"> <h1> Text1 <p class="p-10 text-4xl"> Text1 </p> </h1> </div> </body> </html>
内容的提问来源于stack exchange,提问作者BingBongUser
相关产品推荐
相关产品推荐

