使用CSS设置单个边距
CSS允许我们控制元素各个边的周围空间。CSS margin属性是以下属性的简写:margin-top、margin-right、margin-bottom和margin-left。
语法
CSS margin属性的语法如下:
Selector {
margin-top: /*value*/
margin-right: /*value*/
margin-bottom: /*value*/
margin-left: /*value*/
}
值可以是以下之一:
长度 - 以px、pt等设置边距。默认为0
% - 以百分比设置边距
auto - 网页浏览器自动计算边距
假设我们使用简写属性设置了以下边距:
margin: 25px 30px 50px 60px;
以上表示:
顶部边距为25像素
右侧边距为30像素
底部边距为50像素
左侧边距为60像素
我们可以这样设置单个边的边距:
margin-top: 25px; margin-right: 30px; margin-bottom: 50px; margin-left: 60px;
以下示例说明了CSS margin属性:
设置margin auto
使用值为auto的margin属性,边距由网页浏览器自动调整:
margin-left: auto;
示例
让我们来看一个例子:
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin-left: auto;
margin-bottom: 4em;
width: 30%;
padding: 0.6rem;
box-shadow: inset 0 0 3px turquoise;
outline: thin dotted;
text-align: center;
}
div + div {
margin-right: 30%;
box-shadow: inset 0 0 6px teal;
}
div + div + div {
margin-left: 45%;
margin-top: -190px;
box-shadow: inset 0 0 6px orange;
}
</style>
</head>
<body>
<div>
This is demo text
</div>
<div>One (different margins)</div>
<div>Two (different margins)</div>
</body>
</html>
为div设置边距
这里,我们为网页上的多个容器设置了边距:
margin-top: 7%; margin-left: 25%;
我们也设置了负值:
margin-bottom: -3em;
示例
让我们来看一个例子:
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin-top: 7%;
margin-left: 25%;
margin-bottom: -3em;
width: 40px;
height: 40px;
padding: 0.6rem;
box-shadow: inset 0 0 3px turquoise;
border-top-right-radius: 100px;
}
div + div {
margin-right: 30%;
border-top-right-radius: unset;
border-top-left-radius: 100px;
box-shadow: inset 0 0 6px teal;
}
div + div + div {
margin-left: 25%;
margin-top: -140px;
box-shadow: inset 0 0 6px orange;
border-bottom-right-radius: 100px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP