如何在设置了text-align:center的header中添加左上角Logo链接
解决Header左上角Logo超链接定位问题
问题根源
你当前的代码里,#topleft用了绝对定位,但header没有设置position: relative,所以这个元素是相对于整个文档而不是header定位的——这就是为什么top:0会贴页面顶部,调top值时会大幅移动(因为参考系是整个页面)。另外left:10没加单位,浏览器解析会出问题,还有代码里多了个多余的</div>标签。
修复方案
- 给header添加
position: relative,让绝对定位的子元素以header为参考系 - 给
left属性补上单位(比如10px) - 调整
top值就能在header内部微调位置了 - 清理冗余的
</div>标签,保证HTML结构合法 - 可以给header加
min-height或padding,避免Logo超出header范围
修改后的完整代码
<header style="position: relative; text-align: center; min-height: 140px;"> <h1>Homepage</h1> <style type="text/css"> #topleft { position: absolute; left: 10px; /* 补上px单位 */ top: 10px; /* 现在可以微调这个值,相对于header顶部 */ display: block; height: 140px; width: 140px; background: url(images/DSC_0416-1.jpg) no-repeat; text-indent: -999em; text-decoration: none; } </style> <a id="topleft" href="index.html" title="TopLeft">Top Left Link Text</a> </header>
额外优化建议
- 如果想让Logo和header顶部完全对齐,把
top:10px改成top:0即可,现在它会贴header的顶部而不是页面顶部 - 可以给header加
padding-top来调整标题和Logo的垂直间距,避免标题被Logo遮挡
内容的提问来源于stack exchange,提问作者3DPrintingLife
相关产品推荐
相关产品推荐

