margin的无边界问题以及图片的block属性问题

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width,initial-scale=1">

<title>Document</title>

<style>

*{

padding:0;

margin:0;

}

html{

height:100%;

font-size:100px;

}

body{

height:100%;

}

.top-img{

   width:100%;

   height:0.4rem;

   position:absolute;

   left:0;

   top:0;

}

.div1{

margin-top:1rem;

width:100%;

height:1rem;

background:red;

}

.div2{

width:100%;

height:1rem;

background:blue;

}

</style>

</head>

<body>

<img src="p_w_picpaths/ms_01.png" alt="" class="top-img">

<div class="div1"></div>

<div class="div2"></div>

<script>

var screenW = document.documentElement.offsetWidth || document.body.offsetWidth;

console.log(screenW)

var nowW = screenW/640 * 100;

var oHtml = document.getElementsByTagName('html')[0];

oHtml.style.fontSize = nowW + 'px';

console.log(nowW)

</script>

</body>

</html>


 这是移动端开发的一个小测试。按照上面的代码,最终的结果是页面产生了滚动条,为啥呢!!!,纠结死。。。

究其原因,发现其实是margin的无边界问题,.top-img设置了绝对定位,所以在给.div1加上margin-top后由于没有相对的边界所以body的高度被撑开了所以就有了滚动体。

解决办法,去掉.top-img的绝对定位改为:

.top-img{

    width:100%;

    height:0.4rem;

}

以为这样就行了,no!,这个时候.top-img会把上面下面都撑开一段距离,不止3像素,不知道到底是啥原因,反正再加上display:block就搞定了。。。