像这种页面顶部的渐变背景块,一般你们用什么方式定位?position?float?
我一般用position,但是感觉不好用,各位大佬还有什么更好的方式吗?
像这种页面顶部的渐变背景块,一般你们用什么方式定位?position?float?
我一般用position,但是感觉不好用,各位大佬还有什么更好的方式吗?
推荐使用position: fixed
结合伪元素实现,这是目前最主流且维护性最好的方案:
body::before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 400px; /* 根据实际渐变高度调整 */
background: linear-gradient(180deg, #8B5CF6 0%, #EC4899 100%);
z-index: -1; /* 确保内容在渐变层之上 */
}
优势说明:
fixed
定位保证渐变始终覆盖可视区域顶部z-index: -1
使内容自然覆盖在背景之上注意事项:
主内容区域需要设置适当的上边距:
main {
margin-top: 400px; /* 与渐变高度一致 */
position: relative;
}
@media
查询调整高度position: absolute
如果不需要固定的话,直接(随便)写在 body 的 background 里就好了。
如果是固定高度的,可以用
background-attachment
.