Home  >  Article  >  Web Front-end  >  css水平居中,竖直居中技巧_html/css_WEB-ITnose

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

WBOY
WBOYOriginal
2016-06-24 11:46:581107browse

要点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

<html><head></head><body><div id="alert">    <div class="alert-header" style="display: none;">信息提示</div>    <div class="alert-message">GOOD</div>    <div class="alert-footer">        <div class="btn-close">确定</div>    </div></div></body></html>

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;    }

 运行效果

运行时实际尺寸

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn