用CSS来控制实现div的外边距margin

2025-10-09 19:40:23

1、首先我来创建一个div的区块,设置height:150px,width:150px;在div中输入提示文字,具体的代码如下:

<html>

<head>

<title>div和边距</title>

<style type="text/css">

#contion{

background:orange;

border: 1px solid red;

height:150px;

width:150px;

}

</style>

</head>

<body>

<div id="contion">

我是div

</div>

  </body>

</html>

具体的效果如下图所示,可以看到一个矩形的黄色背景的区块。

用CSS来控制实现div的外边距margin

2、我们使用左边的外边距属性值为auto,来看看效果,具体的代码如下:

<html>

<head>

<title>div和边距</title>

<style type="text/css">

#contion{

background:orange;

border: 1px solid red;

height:150px;

width:150px;

margin-left:auto;

}

</style>

</head>

<body>

<div id="contion">

我是div

</div>

  </body>

</html>

通过执行结果,发现这个区块在右边来了,这是为什么呢?设置auto的意思就是左边自动扩展,所以到右边了。

用CSS来控制实现div的外边距margin

3、我们可以使用固定的值来设置这个区块看离左边固定像素位置,具体的倘驼败代码如下:

<html>

<head>

<title>div和边距</title>

<style type="text/css">

#contion{

background:orange;

border: 1px solid red;

height:150px;

width:150px;

margin-left:100px;;

}

</style>

</head>

<body>

<div id="contion">

我是div

</div>

  </body>

</html>

具体的效果如下图所示,这个区块离左边100px的位置显示 了。

用CSS来控制实现div的外边距margin

4、如压轿果我们左边和右边都自动是什么个情况呢?具体的来看如下代码:

<html>

<head>

<title>div和边距</title>

<style type="text/css">

#contion{

background:orange;

border: 1px solid red;

height:150px;

width:150px;

margin-left:auto;

margin-right:auto;

}

</style>

</head>

<body>

<div id="contion">

我是div

</div>

  </body>

</html>

发现这个区块在浏览器的中间了,因为左边和右边都是自动扩展了,所以都自动的平分了。

用CSS来控制实现div的外边距margin

5、我们在HTML中需要让区块是从0,0这个像素位置开始的该怎么做呢?具体率悦的代码如下:

<html>

<head>

<title>div和边距</title>

<style type="text/css">

body{margin:0;}

#contion{

background:orange;

border: 1px solid red;

height:150px;

width:150px;

}

</style>

</head>

<body>

<div id="contion">

我是div

</div>

  </body>

</html>

可以看到body的外边距设置成0px了,所以div框的左上角的左边点为0,0。就有了如下图所示的执行结果。

用CSS来控制实现div的外边距margin

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢