html中怎么让div居中

发布时间:2022-03-04 16:46:50 作者:iii
来源:亿速云 阅读:192

这篇文章主要介绍了html中怎么让div居中的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇html中怎么让div居中文章都会有所收获,下面我们一起来看看吧。

margin方法

可以通过margin来使得div居中,通过给margin-left设置的值为父元素的宽减去子元素的宽再除以2(本例中:(400-100)/2=150px),margin-top的值为父元素的高度减去子元素的高度值再除以2(本例中:(300-100)/2=100px)

例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<style>

.box{

width:400px;

height: 300px;

border: 1px solid #ccc;

}

.box1{

width:100px;

height: 100px;

background-color: pink;

margin-left: 150px;

margin-top:100px;

}

</style>

</head>

<body>

<div>

  <div></div>

</div>

</body>

</html>

效果图:

html中怎么让div居中

position方法

可以通过定位的方法来使得div垂直居中,我们可以设置子元素绝对定位,另外设置top和left值为50%,但是需要注意一点在用定位是也要设置margin值,其中margin-left与margin-right的值都为负值,且值的大小是子元素宽高的一半

例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<style>

    .box{

         width:400px;

         height: 300px;

         border: 1px solid #ccc;

         position: relative;

    }

    .box1{

        width:100px;

        height: 100px;

        background-color: pink;

        position: absolute;

        top: 50%;

        left: 50%;

        margin:-50px 0 0 -50px     

        }

    </style>

</head>

<body>

<div class="box">

<div class="box1"></div>

</div>

</body>

</html>

效果图:

html中怎么让div居中

关于“html中怎么让div居中”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“html中怎么让div居中”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. html中让div居中的方法
  2. 怎么让横向排列的几个浮动的子div居中显示

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

html div

上一篇:Vue怎么清空对象

下一篇:DIV+CSS规范命名的知识点有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》