几个div并列显示效果消除之间的间隔

今天在做一个静态页面时,头部的广告条是很大一张图片,考虑到网页访问时的加载速度,因此需要把一幅图拆成几个尺寸较小的图片来作为背景图,但是采用div来布局时,出现了div不能显示在一行的情况,所以开始想到用display:inline-block来处理,这样是显示到一行了,但是两个div之间有间隔,于是又想到直接用marg-left:-xxpx,将其拖过去,但是在一个浏览器中可以,一旦换了一个浏览器就不行了,特别是ie,才发现这种方法太不好了,于是,后来用了float方法来处理,不再用margin负值将其拖过去,直接上代码:

不加float时:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        body{
            margin:0;
            padding:0;
        }
        .main{
             600px;
            overflow: hidden;
            height:342px;
            margin:0;
            padding:0;
            background: red;;
        }
        .cnt{
            182px;
            height:342px;
            background: red;
            display: inline-block;

        }
        .fst{
            background: url(img/1.jpg) no-repeat;
        }
        .sec{
            background: url(img/2.jpg) no-repeat;
        }
        .trd{
          background: url(img/3.jpg) no-repeat;
         }

    </style>
</head>
<body>
<div class="main">
    <div class="cnt fst"></div>
    <div class="cnt sec"></div>
   <div class="cnt trd"></div>
</div>
</body>
</html>

结果:

这是没有向.cnt中添加float:left时结果,添加之后:如下所示:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        body{
            margin:0;
            padding:0;
        }
        .main{
             600px;
            overflow: hidden;
            height:342px;
            margin:0;
            padding:0;
            background: red;;
        }
        .cnt{
            182px;
            height:342px;
            background: red;
            display: inline-block;
            float: left;
        }
        .fst{
            background: url(img/1.jpg) no-repeat;
        }
        .sec{
            background: url(img/2.jpg) no-repeat;
        }
        .trd{
          background: url(img/3.jpg) no-repeat;
         }

    </style>
</head>
<body>
<div class="main">
    <div class="cnt fst"></div>
    <div class="cnt sec"></div>
   <div class="cnt trd"></div>
</div>
</body>
</html>

  结果为:

如果是竖着排列的两个div,为了消除他们之间的间隔,可以使用div{margin:0;padding:0}来进行设置,因为每个浏览器都有一套自己的方式来解析网页,div内部存在着内边距和外边距,所以可以先清除边距来消除div之间的间隔。

原文地址:https://www.cnblogs.com/laogai/p/3372617.html