最新更新 sitemap 网站制作设计本站搜索
网页设计
国外网站 韩国网站 个人主页 手提袋设计 CSS 网页特效 平面设计 网站设计 Flash CMS技巧 服装网站 php教程 photoshop 画册 服务器选用 数据库 Office
虚拟主机 域名注册 云主机 网页设计 客服QQ:8208442

CSS实现元素相对于浏览器窗口进行定位

日期:07-23    来源:中国设计秀    作者:

网页制作cnwebshow文章简介:css实现相对浏览器窗口定位彻底研究.
Q2V中国设计秀

Web Developer / Designer 经常需要将一个元素“固定”在页面的某个位置。例如弹出窗口、漂浮广告位等……本文将详细介绍简单css实现元素相对于浏览器窗口进行定位的方法。Q2V中国设计秀

position_fixedQ2V中国设计秀

position:fixed生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。Q2V中国设计秀

良好支持 W3C 标准的浏览器实例Q2V中国设计秀

在 IE9、Firefox、Chrome等良好支持 W3C 标准的浏览器中,如果我们希望将某元素绝对定位于窗口正中间,我们可以给它指派这样的 css样式:Q2V中国设计秀

width:336px;
height:280px;
left:50%;
top:50%;
margin-left:-168px;
margin-top:-140px;
position:fixed;

这里 margin-left 、margin-top 的值应该修改为您页面主要区域宽度和高度的一半。Q2V中国设计秀

修正IE版本<7不支持position:fixed的bugQ2V中国设计秀

IE版本<7的浏览器不支持position:fixed属性,所以并未实现期望的效果,这时就要针对IE<7的浏览器写单独的样式。Q2V中国设计秀

(1)利用 Javascript 计算出需要的 top 值Q2V中国设计秀

在head中插入:Q2V中国设计秀

<!--[if IE lt 7]>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<![endif]-->

在style.css样式表中针对目标定位元素样式中写入:Q2V中国设计秀

position:absolute;
top:expression(eval(document.body.scrollTop + 50));

防止滚动条滚动时的闪动,需要定义HTMl的属性为:Q2V中国设计秀

html {
    background-image: url(about: blank); /*用浏览器空白页面作为背景*/
    background-attachment: fixed; /*确保滚动条滚动时,元素不闪动*/
}

在 IE 中特有的 css 运算符 expression中我们可以利用 Javascript 计算出需要的 top 值,这样就达到了与 position: fixed 同样的效果。Q2V中国设计秀

(2)利用容器对溢出内容的处理方式来实现Q2V中国设计秀

定义body内外边距为0,实现html和浏览器窗口相同大小,使body出现滚动条,元素相对于html相对定位。Q2V中国设计秀

body { padding: 0; margin: 0; }
html { overflow: hidden; }
body { height: 100%; overflow: auto; }

针对IE6定义元素属性:Q2V中国设计秀

position: absolute;
top: 50% ;
left: 50% ;
margin-top: -140px;
margin-left: -168px;

让元素固定于浏览器Q2V中国设计秀

分别让元素定位于浏览器左侧、右侧、顶部、底部综合样式演示:Q2V中国设计秀

position:absolute;
bottom:auto;
top:expression(eval(document.documentElement.scrollTop));/* IE6 头部固定 */
position:absolute;
right:auto;
left:expression(eval(document.documentElement.scrollLeft+document.documentElement.clientWidth-this.offsetWidth)-(parseInt(this.currentStyle.marginLeft, 10)||0)-(parseInt(this.currentStyle.marginRight, 10)||0));/* IE6 固定右侧 */
position:absolute;
bottom:auto;
top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop, 10)||0)-(parseInt(this.currentStyle.marginBottom, 10)||0)));/* IE6 固定底部  */
position:absolute;
right:auto;
left:expression(eval(document.documentElement.scrollLeft));/* IE6 左侧固定 */