HTML和CSS——背景图固定

效果:

对于不规则图片,在屏幕缩小时图片适当左移,但为了不遮挡左侧文字,左移至一定位置后图片固定位置。

 

方法:

给背景图片设置宽度和absolute定位,使得图片浮于页面。然后在js里边判断当前窗口大小,当页面小到会致使图片遮挡左侧文字时,给图片添加left属性,这样图片就不会再向左移动了(如果文字在右侧就添加right属性)。

html

<body> <img class="backImg" src="img/backimg.png"> <div id="container"> </div></body>

css

body { margin: 0px; min-width: 1920px; min-height: 800px; overflow: hidden;}.backImg { width: 1530px; position: absolute; right: 0; top: 0;}#container { position: fixed;
   bottom: 250px;
   width
: 383px; display: flex; flex-direction: column; justify-content: center; margin-left: 131px;}

js

window.onload=function(){ if($(window).width()<=1660){ $(‘.backImg‘).attr(‘style‘,‘left:150px;‘); }}$(window).resize(function(){ if($(window).width()<=1660){ $(‘.backImg‘).attr(‘style‘,‘left:150px;‘); } else{ $(‘.backImg‘).removeAttr(‘style‘); }})

 

相关文章