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 ~ ~ 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值