CSS中top属性失效问题:如何用top而非margin-top定位元素
解决top属性不生效的问题
top属性只对position值为relative、absolute、fixed或sticky的元素生效,而HTML元素默认的position是static,所以你给.h1设置top:100px不会产生任何效果。
要让top属性生效,只需给.h1添加合适的position属性即可,最常用的是relative(不会脱离文档流,仅相对于自身原有位置偏移):
.hover { color: #fff0; background: linear-gradient(90deg, gold 50%, #fff 0) var(--_p, 100%)/200% no-repeat; -webkit-background-clip: text; background-clip: text; transition: 3s; font-family: system-ui, sans-serif; font-size: 2rem; line-height: 1.5; max-width: 23.2%; margin-left: 120px; } .h1 { position: relative; /* 新增该行,让top属性生效 */ top: 100px; }
如果需要元素脱离文档流(不占据原有空间),可以改用position: absolute,但此时要确保它的父元素设置了非static的定位(比如给父级也加position:relative),否则元素会相对于整个视口偏移。
不需要依赖br标签或margin-top,通过设置position和top就能实现你想要的定位效果。
内容的提问来源于stack exchange,提问作者Mor levi
相关产品推荐
相关产品推荐

