我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。


当前回答

父母{ 位置:相对; } 孩子{ 位置:绝对的; 左:50%; 变换:translateX (-50%); } <父> <孩子> 儿童> < / 父> < /

其他回答

出于某种原因,之前的答案对我都不起作用。这对我来说很管用,而且在不同的浏览器中也同样适用:

.center {
    text-align: center;
    height: 100%;

    /* Safari, Opera, and Chrome */
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;

    /* Firefox */
    display: -moz-box;
    -moz-box-pack: center;
    -moz-box-align: center;

    /* Internet Explorer 10 */
    display: -ms-flexbox;
    -ms-flex-pack: center;
    -ms-flex-align: center;
}

在我的情况下,手机屏幕大小是未知的,这是我所做的。

HTML

<div class="loadingImg"></div>

CSS

.loadingImg{
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 9999999;
    border: 0;
    background: url('../images/loading.gif') no-repeat center;
    background-size: 50px 50px;
    display: block;
    margin: 0 auto;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

JavaScript(在需要显示此DIV之前)

$(".loadingImg").css("height",$(document).height());
$(".loadingImg").css("width",$(document).width());
$(".loadingImg").show();

如果你的中心内容深在其他div,那么只有边缘可以拯救你。什么都没有。当我不使用Bootstrap这样的框架时,我总是面临这个问题。

这可以通过flex容器轻松实现。

.container{
 width: 100%;
 display: flex;
 height: 100vh;
 justify-content: center;
}

.item{
 align-self: center;
}

预览链接

使用justify-content和align-items水平和垂直对齐div

https://developer.mozilla.org/de/docs/Web/CSS/justify-content https://developer.mozilla.org/en/docs/Web/CSS/align-items

超文本标记语言 的身体, .container { 高度:100%; 宽度:100%; } .container { 显示:flex; 对齐项目:中心; justify-content:中心; } .mydiv { 宽度:80 px; } < div class = "容器" > <div class="mydiv">h & v aligned</div> < / div >