当我调整浏览器窗口大小时,如何保持div垂直居中?

8

我想让一个div在垂直方向上居中,但是当我调整浏览器窗口大小时它不起作用。

如何修改以实现可调节的margin-top?

谢谢

<script>    
var h = $(window).height();
var parentHeight = h;   
var childHeight = $('#a-middle').height();      
$('#a-middle').css('margin-top', (parentHeight - childHeight) /2);
</script>
编辑: 由于flexbox无法在IE-9上工作,因此答案应该使用js。

1
你必须支持IE9吗?否则,你可以在不使用JavaScript的情况下使用Flexbox:http://caniuse.com/#search=flex - ChaosClown
1
你能提供一段代码片段来展示问题吗? - vdubus
14个回答

12

你应该坚持使用CSS解决方案,虽然有几种方法可以实现这一点。

.alignVertical {
    position:relative;
    display:inline-block;
    top:50%;
    transform:translateY(-50%);
}

jsfiddle: https://jsfiddle.net/jorjmt70/

或者使用flexbox

.parent {
    display:flex;
    height:100vh;
    background-color:red;
    justify-content:center;
    align-items:center;
    flex-direction:column;
}

jsfiddle: https://jsfiddle.net/mdh9h876/

如果您想使用弹性盒,请使用Autoprefixer以获取更深层次的浏览器支持:https://github.com/postcss/autoprefixer


谢谢你,但是我把你的第一个代码块添加到了#a-middle上,但是没有起作用。 - EnexoOnoma
太棒了,谢谢你。如果我想把它放在中心上方30像素,该如何编辑css? - EnexoOnoma
1
flexbox在ie9中无法工作,您还应该为flexbox和transform添加前缀。 - ChaosClown
使用 margintop 来定义偏移量。 - ChaosClown
有没有任何方法可以在我的现有代码基础上进行构建? - EnexoOnoma
请同时添加您的html和css。 - ChaosClown

4

虽然你可以轻松使用纯CSS实现这一点,但是你的要求是想要JS的答案。

如果你对纯CSS的答案感兴趣,请参考此答案,其中有多种不同的方法来垂直/水平居中元素。


你可以将你的jQuery简化为以下内容:

$('#a-middle').css('margin-top', function () {
    return ($(window).height() - $(this).height()) / 2
});

你可以将这段代码置于一个 resize 事件监听器中,并使用 .resize() 方法来触发浏览器加载时的初始事件。

示例在此

$(window).on('resize', function () {
    $('#a-middle').css('margin-top', function () {
        return ($(window).height() - $(this).height()) / 2
    });
}).resize();

JavaScript等价物(不使用jQuery):

示例在此

var verticalCentering = function () {
    var el = document.querySelector('#a-middle');
    el.style.marginTop = (window.innerHeight - el.offsetHeight) / 2 + 'px';
}
window.addEventListener('resize', verticalCentering);
verticalCentering();

3
对于一个名为'center-me'的div:
$(document).ready(centerDiv);
$(window).resize(centerDiv);

function centerDiv() {
    var winHeight = $(document).innerHeight(),
        divHeight = $('.center-me').height();

    $('.center-me').css('marginTop', (winHeight - divHeight) / 2 );
}

在文档准备就绪时调用它,以使其居中,然后在调整大小事件上保持居中。

这里是它的fiddle:Fiddle


2
为了让一个div始终保持在屏幕中央,您可以在将position属性设置为absolute后使用top和left属性。但是,当浏览器大小改变时,您需要动态设置这些属性。这可以通过使用JQuery方法resize()来完成。
/*css code*/
.div{
   position:absolute;
   top:100px;
   left:50px;
   background:black;
}

/*JS Code*/
function keep_div_centered()
{
     window_height = $(window).height();
     window_width = $(window).width();
     obj_height = $('.keepincenter').height();
     obj_width = $('.keepincenter').width();
     $('.keepincenter').css('top',(window_height/2)-(obj_height/2)).css('left',(window_width/2)-(obj_width/2))
}
keep_div_centered();
$(window).resize(function(){
     keep_div_centered();
})

/* HTML Code */
<div class="keepincenter"></div>

链接到示例 - http://jsfiddle.net/y0937t06/


2
这可以通过简单的CSS实现,且支持IE8及以上版本

html, body { 
    height: 100%;
}

.parent {
    display: table;
    table-layout: fixed;
    width: 100%;
    height: 100%;
}

.child {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    background: red;
}
<div class="parent">
    <div class="child">This is always centered.</div>
</div>

使用 table-layout 会变得简单:子元素可以垂直对齐(顶部,中间,底部)并占用所有可用高度。您不需要使用 JavaScript,具有不完全支持的 CSS 或硬编码任何数字,它应该只需正常工作。
根据您要做的具体内容,可能需要使用 flexbox 或 - 作为最后的选择 - 需要使用 JavaScript,但对于大多数情况,display: table-cell 是您的朋友。
话虽如此,如果旧版浏览器可以获得不同的布局,则只需使用 @Victor 的答案:这就是 flexbox 的用途。

好的解释。没有JavaScript也很棒。 - Ranjith Siji

2
一种CSS解决方案可以帮助你解决问题。

div.center {
  height: 100px;
  width: 300px;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -150px;
  position: absolute;
  background-color: red;
}
<div class="center">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>

这个CSS代码在IE8+、Firefox和Chrome中都可以很好地工作。

但是你必须知道要正确调整DIV的大小。如果高度和宽度是动态的,你只需要用JavaScript相应地更新样式。不要忘记在需要时在JS中将class center 应用到你的DIV上。

解释:

  • margin-top : - height / 2 是因为 top : 50% 只会将DIV的顶部垂直居中。
  • margin-left : - width / 2 是因为 left : 50% 只会将DIV的左侧水平居中。
  • position : absolute 以使DIV可以在整个页面上居中。

1
$(window).resize(function () {
var h = $(document).height();
var parentHeight = h;
var childHeight = $('#imagegallery').height();
$('#imagegallery').css('margin-top', (parentHeight - childHeight) / 2);
            });

1
对我而言,这是CSS的圣杯 :) 我找到的最可靠的方法是将容器元素设置如下:
display: -webkit-flex;
-webkit-justify-content: center; /* horizontal */
-webkit-align-items: center; /* vertical */

这很简单,不需要任何其他CSS属性的先决条件。

下面的代码将内容放置在垂直居中的上方30像素处:

#container {
  width: 500px;
  height: 300px;
  background-color: red;
  display: -webkit-flex;
  -webkit-justify-content: center;
  -webkit-align-items: center;
}
#content {
  background-color: green;
  margin-bottom: 30px;
}
<div id="container">
  <span id="content">Content</span>
</div>


0

当您想要垂直和水平居中绝对定位的 div 时,此方法非常有用。它也适用于 IE8

您需要将外部和内部 div 都设置为

position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;  

margin:auto 在这种情况下是将 div 居中的基本方法。

您还可以设置 .in div 的高度和宽度,仍然可以在垂直居中时看到它,并且在调整浏览器大小时也会居中。

* {
    margin: 0;
    padding: 0;
}
html, body {
    position: relative;
    height: 100%;
    width: 100%;
}
.in, .out {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;  
}
.in {
    background-color: red;
    height: 50%;
    width:50%;
 }
.out {
    background-color: blue;
}

示例1 JSFIDDLE 高度,宽度:以百分比表示:http://jsfiddle.net/a_incarnati/1o5zzcgh/3/

示例2 - JSFIDDLE 固定高度,固定宽度 http://jsfiddle.net/a_incarnati/1o5zzcgh/4/


0
将display: table-cell;应用于父元素,并使用vertical-align属性垂直对齐内容,同时给予上方所需的间距进行调整。
.child{
    display:table-cell;
    vertical-align:top;
    padding-top: 50px;
}

这将使边距保持一致。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接