如何解决Squarespace头部导航项hover时的布局偏移问题
问题原因
字体加粗后字符实际占位宽度会变大,默认情况下元素宽度会跟随内容变化,因此触发hover时容器宽度增加挤压周围布局,产生偏移效果。
解决方案
方案1:使用text-stroke预留宽度(推荐)
兼容性好,支持平滑过渡效果,是最常用的解决方案:
/* 给所有导航链接默认添加透明描边,提前预留出加粗后的宽度 */ .header-nav-folder-item a, .header-nav-item--collection a, .header-nav-item--external a { -webkit-text-stroke: 0.6px transparent; transition: all 0.2s ease; } /* hover时设置加粗,也可以直接修改text-stroke颜色实现加粗效果,过渡更顺滑 */ .header-nav-folder-item:hover a, .header-nav-item--collection:hover a, .header-nav-item--external:hover a { font-weight: 550; /* 替换font-weight的写法:-webkit-text-stroke: 0.6px [你的文字实际颜色]; */ }
方案2:伪元素预占宽度
对兼容性要求更高的场景可以用该方案,通过不可见的加粗伪元素提前撑开容器宽度:
.header-nav-folder-item a, .header-nav-item--collection a, .header-nav-item--external a { position: relative; } .header-nav-folder-item a::before, .header-nav-item--collection a::before, .header-nav-item--external a::before { content: attr(data-text); font-weight: 550; display: block; height: 0; overflow: hidden; visibility: hidden; }
使用该方案需要给每个导航a标签添加data-text属性,属性值和链接显示的文本完全一致,例如<a href="/home" data-text="首页">首页</a>
方案3:固定导航项最小宽度
如果导航项文本长度差异不大,可以直接给每个导航项设置足够容纳加粗文本的最小宽度:
.header-nav-folder-item, .header-nav-item--collection, .header-nav-item--external { min-width: 80px; /* 数值根据实际导航文本长度调整 */ text-align: center; }
内容的提问来源于stack exchange,提问作者Andrew Swayze
相关产品推荐
相关产品推荐

