html中如何让div居中


本文摘自PHP中文网,作者清浅,侵删。

html中使得div居中的方法有:margin方法通过设置margin的左边距和上边距的值为父元素减去子元素再除以2的值来使div居中;另外position方法也可以使div居中

在页面布局时经常会将网页的主体部分居中在页面上,这就需要我们实现div水平居中,接下来将在文章中为大家具体介绍如何使得div居中在页面中,具有一定的参考价值,希望对大家有所帮助

【推荐课程:HTML教程】

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>

效果图:

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>

效果图:

本文参考:https://www.html.cn/doc/html/layout/

HTML标签索引:https://www.html.cn/sitemap.html

总结:以上就是本篇文章的全部内容了,希望通过这篇文章可以帮助大家学会如何将div居中在页面上

以上就是html中如何让div居中的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

css margin属性怎么用

css如何让div居中?css实现div居中的方法

css中margin不起作用的原因及解决方法

html中如何让div居中

上下margin重叠传递问题

“margin:0 atuo;”是什么意思?

css如何实现图片在div中垂直居中

div在屏幕中如何实现水平居中和垂直居中

css中的margin是什么意思

css怎么让div居中

更多相关阅读请进入《div居中》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...