欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

css水平居中,竖直居中技巧_html/css_WEB-ITnose

程序员文章站 2022-04-12 23:52:44
...
要点1:容器设置【position: absolute;】

要点2:容器设置【top: 50%;left: 50%;】

要点3:要知道容器实际的width和heigh(可以是预设的,也可以是运行时动态获取到的)

要点4:水平居中:margin-left = -1*(width/2),例如width是280px,则设置【margin-left:140px;】

要点5:竖直居中:margin-top = -1*(height/2),例如height是110px,则设置【margin-top:55px;】

例子如下:

html

GOOD

css

    #alert {        position: absolute;        width: 280px;        top: 50%;        left: 50%;        margin-top: -55px;        margin-left: -140px;        border-radius: 5px;        background: #fff;        z-index: 1000000;        padding: 20px;    }

运行效果

运行时实际尺寸