如何在所有屏幕尺寸中将一个字形对齐到页面中间

时间:2014-09-15 08:09:48

标签: javascript jquery html css

我有一个glyphicon,我必须始终在页面中间对齐,无论它显示的屏幕大小如何,我将如何实现此目标以及我哪里出错?

HTML

<div id='overlay'>
    <div class="container">
        <div class="middle-loading-box">
            <div class="center-block">
                <span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span>
            </div>
        </div>
    </div>
</div>

CSS

.glyphicon-refresh-animate {
    -animation: spin .7s infinite linear;
    -webkit-animation: spin2 .7s infinite linear;
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg);}
    to { -webkit-transform: rotate(360deg);}
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg);}
    to { transform: scale(1) rotate(360deg);}
}

.middle-loading-box .div.center-block .glyphicon{
    margin: 0 auto;

}
.middle-loading-box{
    border: none;
    width: 38px;
    height: 36px;
    margin: 0 auto;
    display: block;
    text-align:center;
    padding-top:1px;
}
.glyphicon-refresh:before ,.glyphicon-refresh:after{
    color: orange;
    font-size: 30px;
    text-align:center;
}

JQUERY

$(function() {
    var docHeight = $(document).height();
    $("body").append("<div id='overlay'></div>");
    $("#overlay")
    .height(docHeight)
    .css({
        'opacity' : 0.7,
        'position': 'absolute',
        'top': 0,
        'left': 0,
        'background': '#000000',
        'width': '100%',
        'z-index': 5000
    });
});

链接到我的JS.fiddle

4 个答案:

答案 0 :(得分:3)

添加

   position: fixed;
   top: 50%;
   left: 50%;
   margin-top:-16px;
   margin-left:-16px;

.middle-loading-box

http://jsfiddle.net/f709psLh/2/

答案 1 :(得分:3)

这是你正在寻找的吗?

http://css-tricks.com/centering-in-the-unknown/

答案 2 :(得分:2)

也许是一个更简单的解决方案:

.glyphicon {
    position: absolute;
    top:50%; 
}

答案 3 :(得分:2)

另一种解决方案是使用display: table,如下所示:

<强> JS

$(function () {
    var docHeight = $(document).height();
    $("body").append("<div id='overlay'></div>");
    $("#overlay")
        .height(docHeight)
        .css({
        'opacity': 0.7,
            'position': 'relative',//change position to relative
            'top': 0,
            'left': 0,
            'background': '#000000',
            'width': '100%',
            'z-index': 5000,
            'display': 'table'// add display table
    });
});

<强> CSS

.container {
    display: table-cell;/*Add display table cell*/
    vertical-align: middle;/*Add vertical align middle*/
}

fiddle