无法将.workButton居中及a标签对齐问题求助
问题排查与优化建议
嘿,我帮你梳理下这两个问题的原因和解决办法:
一、.workButton 无法居中的问题
你现在给 .workButton 加的 text-align: center 是无效的,因为它本身是行内元素(a标签默认是行内),这个属性只会控制按钮内部文本的对齐,没法让按钮自身在父容器里居中。
有两种简单的解决思路:
- 给按钮的父元素
#hero添加text-align: center,利用行内元素在块级父元素中靠文本对齐属性居中的特性:
#hero { max-height: 600px; height: 100vh; background-color: #87509c; text-align: center; /* 新增这行 */ h1 { /* 原有样式不变 */ text-align: center; color: #f7f3ea; font-size: 42px; line-height: 50px; margin-top: 140px; margin-bottom: 60px; } .workButton { /* 去掉自身的 text-align: center,保留其他样式 */ font-size: 18px; font-weight: 600; color: #ffffff; padding: 20px 80px; text-transform: uppercase; text-decoration: none; border: 1px solid #eb7d4b; border-radius: 5px; background-color: #eb7d4b; box-shadow: 0 2px #c86a40; } }
- 把按钮转为块级元素,再用
margin: 0 auto居中:
.workButton { display: block; /* 转为块级元素 */ width: fit-content; /* 让宽度适配内容,不然默认占满父容器 */ margin: 0 auto; /* 水平居中 */ /* 其他原有样式不变 */ font-size: 18px; font-weight: 600; color: #ffffff; padding: 20px 80px; text-transform: uppercase; text-decoration: none; border: 1px solid #eb7d4b; border-radius: 5px; background-color: #eb7d4b; box-shadow: 0 2px #c86a40; }
二、导航栏a标签无法对齐的问题
你的导航栏用了 display: flex 布局,但里面的 li 又用了 float: left,这两个布局方式会冲突,导致a标签对齐混乱。应该统一用flex布局来实现横向排列:
修改navbar的SCSS代码:
.navbar { display: flex; margin: 60px 20px 20px 40px; ul { margin-left: auto; list-style-type: none; align-self: center; display: flex; /* 新增flex布局,代替float */ li { /* 去掉 float: left */ a { text-decoration: none; color: #ffffff; padding: 5px 20px; text-transform: uppercase; transition-duration: 1.5s; display: block; /* 让a标签占满li的空间,hover背景更完整 */ } a:hover { background-color: #643a79; border-radius: 3px; transition-duration: .4s; } } } }
这样修改后,导航栏的a标签会整齐地横向排列,hover效果也会更自然。
另外,建议你打开 box-sizing: border-box 的注释,这样元素的padding和border不会撑开宽度,布局会更可控哦~
内容的提问来源于stack exchange,提问作者MichalDusza
相关产品推荐
相关产品推荐

