求助:无法将Logo居中于带滚动背景的Div内
解决Logo在滚动背景容器内居中的问题
我来帮你搞定这个居中的问题~首先咱们先排查现有代码里的小问题,再给出简单可靠的解决方案:
1. 先修复CSS语法错误
你写的#header_block里有个小失误:width: 100% border-bottom: ...这里少了分号,会导致后面的样式失效,先补上:
#header_block { background: transparent url('http://i.imgur.com/1tyMljX.jpg') repeat fixed 0% 0%; width: 100%; height: 139px; border-bottom: 2px solid #2ECC71; /* 补充分号,修正前的width:100%未写分号 */ text-shadow: 0px 1px 0px rgb(39, 33, 59); animation: bganim 20s linear infinite; }
2. 为什么margin:auto和<center>标签没生效?
<center>是HTML4的旧标签,现在已被CSS取代,且它仅能实现行内元素/文本的水平居中,对块级元素的垂直居中无能为力。- 你给
#hb_title加的margin:auto只能实现水平居中,但垂直居中需要父容器提供合适的布局上下文——你的父容器#header_block是普通块级元素,默认流式布局无法让子元素垂直居中。
3. 最优解决方案:用Flex布局实现完美居中
Flex布局是当前实现元素居中最便捷的方式,只需给父容器#header_block加几个属性,就能让子元素#hb_title自动水平+垂直居中:
完整代码示例:
<div id="header_block"> <div id="hb_title"></div> </div>
#header_block { background: transparent url('http://i.imgur.com/1tyMljX.jpg') repeat fixed 0% 0%; width: 100%; height: 139px; border-bottom: 2px solid #2ECC71; text-shadow: 0px 1px 0px rgb(39, 33, 59); animation: bganim 20s linear infinite; /* 新增Flex布局属性 */ display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ } #hb_title { background: url('https://cdn.shopify.com/s/files/1/0580/2885/products/the-prison-server-logo_4d5b6eb2-d630-43d9-b8c0-bd024646ef12_400x400.jpg?v=1510041886'); background-repeat: no-repeat; background-size: contain; /* 让Logo自适应容器大小,避免超出或被裁剪 */ width: 50%; height: 60%; /* 这里margin:auto可以去掉了,Flex已经帮我们搞定居中 */ } /* 补充动画定义(你之前的代码里没写,这是JSFiddle看不到滚动效果的原因) */ @keyframes bganim { from { background-position: 0 0; } to { background-position: 100% 0; } }
额外说明:
- 给
#hb_title加background-size: contain是为了让Logo自适应容器宽高,保证完整显示。 - 补上
@keyframes bganim后,背景的水平滚动效果就能在JSFiddle里正常显示了~
内容的提问来源于stack exchange,提问作者Rhys
相关产品推荐
相关产品推荐

