分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

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

发布时间:2023-09-06 01:53责任编辑:董明明关键词:CSSdiv

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

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

原文地址:https://www.cnblogs.com/tanghm/p/9022923.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved