如何通过CSS将页眉导航栏中的Logo移动到左上角位置
问题根源
你的Logo无法定位到左上角,完全是CSS语法错误和多余样式冲突导致的:
padding属性值不能用逗号分隔:你在.navbar、.navbar.sticky里写的padding: 30px, 0;是语法错误,浏览器直接忽略该样式,导航栏内边距完全失效- 属性用错了对象:
align-items是flex/grid容器的专属属性,你把它写在.navbar .logo a这个普通行内元素上,没有任何效果 - 多余的顶部内边距打乱布局:你给Logo加了
padding-top:30px、给菜单项加了padding-top:18px,两个元素顶部偏移量不一致,不仅垂直错位,也让Logo没法贴合左上角 - 其他零散语法错误:
font-weight: 500px多带了px单位、margin: auto 0. auto 40px多打了小数点、background-color: none的属性值不合法,这些都会导致对应样式失效。
修复方法
你原本给.navbar .max-width写的display: flex; align-items: center; justify-content: space-between;布局逻辑完全正确——flex容器的第一个子元素(Logo)天然靠左,第二个子元素(菜单)天然靠右,只要修正语法错误、删掉冲突的多余样式即可。
把原有导航栏和首页区域的CSS替换为以下代码:
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Ubuntu:wght@400;500;700&display=swap'); * { margin: 0px; padding: 0px; box-sizing: border-box; text-decoration: none; } .max-width { max-width: 1300px; padding: 0 80px; margin: auto; } /* navbar styling */ .navbar { position: fixed; width: 100%; padding: 30px 0; background-color: transparent; font-family: 'Ubuntu', sans-serif; z-index: 999; } .navbar.sticky { padding: 15px 0; background: crimson; } .navbar .max-width { display: flex; align-items: center; justify-content: space-between; } .navbar .logo a { color: #fff; font-size: 35px; font-weight: 600; } .navbar .logo a span { color: crimson; } .navbar .menu li { list-style: none; display: inline-block; } .navbar .menu li a { color: #fff; font-size: 18px; font-weight: 500; margin-left: 25px; transition: color 0.3s ease; } .navbar .menu li a:hover { color: crimson; } /* home section styleing */ .home { display: flex; background-size: cover; background-attachment: fixed; background-image: url(/banner.jpg); background-repeat: no-repeat; background-position: center; height: 100vh; color: #fff; min-height: 500px; font-family: 'Ubuntu', sans-serif; } .home .max-width { margin: auto 0 auto 40px; } .text-1 { font-size: 27px; } .text-2 { font-size: 75px; font-weight: 600; } .text-3 { font-size: 40px; margin: 5px 0; } .home .text-3 span { color: crimson; font-weight: 500; }
修改后Logo会自动固定在导航栏左上角,和右侧菜单保持垂直居中对齐,导航吸顶切换样式的逻辑也能正常生效。
内容的提问来源于stack exchange,提问作者Baljit Singh
相关产品推荐
相关产品推荐

