CSS入门指南——如何撑起一个div?width/margin/padding随谈

一个div是如何被撑起来的? width(自身宽度)+ padding(内边距)+ margin(外边距) 


首先是自身宽度,我们可以设置宽度,那么div中的元素如果没有设置样式会从这个div的左上角开始排列。

我们来通过一个实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<style>
    body{
        margin:0;
    }
    .main{
        background:#ddd;
        width:300px;
    }
</style>
</head>
<body>
    <div class="main">
      C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cross-platform C and C++ development using VS Code on Windows, Linux, and macOS. The extension is still in preview and our focus is code editing, navigation, and debugging support for C and C++ code everywhere that VS Code runs.
    </div>
</body>
</html>

这时我们只给了宽度,看一下效果图

 

 我们会发现如果只有自身的宽度,这个文本的排版会显得很拥挤 ,那么如果将文本从内部撑开呢?我们可以为这个div加一点内边距

 .main{
        background:#ddd;
        width:300px;
        padding:20px 50px;
    }

我们加了上下20px,左右50px的内边距,然后效果如下:

  

 这样就舒服多了,我们也可以看出来内边距的效果是显示在div内部的,内边距的地方也会有背景色。

那我们要怎么把两个紧挨的div分开,让他们有一定的间隔呢,这就需要外边距了

在上面的基础上,我们再加上一行代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<style>
    body{
        margin:0;
    }
    .main{
        display: inline-block; /*div块状元素,此处将它设置为行内块元素*/
        background:#ddd;
        width:300px;
        padding:20px 50px;
        margin:20px 10px;
    }
</style>
</head>
<body>
    <div class="main">
      C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cross-platform C and C++ development using VS Code on Windows, Linux, and macOS. The extension is still in preview and our focus is code editing, navigation, and debugging support for C and C++ code everywhere that VS Code runs.
    </div>
    <div class="main">
            C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cross-platform C and C++ development using VS Code on Windows, Linux, and macOS. The extension is still in preview and our focus is code editing, navigation, and debugging support for C and C++ code everywhere that VS Code runs.
          </div>
</body>
</html>

然后我们看效果,两个相同的div被外边距撑开了,我们也能看到外边距是独立在元素外部的,没有背景色。

 

总结一下,内外边距的的作用:

内边距——向内占宽度

外边距——向外占宽度


补充:margin,padding的书写方法

padding:20px;
margin:20px;

 上下左右都为20px

padding:20px 10px;
margin:20px 10px;

 上下为20px,左右为10px

padding:20px 10px 30px;
margin:20px 10px 30px;

 上为20px,左右为10px,下为30px

padding:20px 10px 30px 40px;
margin:20px 10px 30px 40px;

 上20px,右10px,下30px,左40px

ENDING ~ ~ 

猜你喜欢

转载自www.cnblogs.com/tanghm/p/9022923.html