移动端嵌套Div(id=portrait)无法居中问题求助
解决嵌套Div中portrait元素的移动端居中问题
问题根源
- ID拼写错误:媒体查询里误写为
#potrait,正确ID是#portrait,导致移动端样式完全不生效 - 原有样式冲突:
#portrait默认设置了float:right和display:inline-block,这两个属性会破坏margin:0 auto的居中逻辑
修改后的CSS代码
#ABOUT-ME { top:650px; height:350px; z-index:4; width:70%; position:absolute; left:50%; -webkit-transform: translate(-50%, 0); transform: translate(-50%, 0); } .about-me-box { position:absolute; top:110px; z-index:4; width:100%; white-space: nowrap; margin:auto; height:450px; overflow:auto; left:50%; -webkit-transform: translate(-50%, 0); transform: translate(-50%, 0); border:1px solid rgba(255, 255, 255, 0.15); } #aboutme { display:flex; color:#000; position:absolute; background-image: linear-gradient(90deg, #FFE600, #00fbff); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size:50px; top:0px; } #portrait { width:200px; height:300px; display:inline-block; margin:60px; right:50px; background-color:#000; float:right; } @media (max-width: 1020px) { /* 修正ID拼写,重置冲突样式实现居中 */ #portrait { float: none; display: block; margin: 60px auto; /* 保持上下间距,实现水平居中 */ } .about-me-box { height:850px; white-space: normal; /* 取消强制不换行,避免移动端内容溢出 */ } #_1 { width:80%; margin-top:70px; } #_2 { width:80%; } }
额外优化说明
- 给
.about-me-box添加white-space: normal;,取消默认的强制不换行规则,避免移动端文本超出容器范围 - 移动端使用
display:block配合margin:auto是最稳定的水平居中方案,不会受浮动、行内元素等属性干扰
内容的提问来源于stack exchange,提问作者Gift G.
相关产品推荐
相关产品推荐

