如何在不知道父高的情况下垂直居中div?

时间:2014-01-31 17:08:07

标签: jquery css responsive-design center absolute

您好希望您能帮助我。我试图垂直居中一个div,但我一直在失败。 我认为问题在于div是由2个元素组成的画廊 - 主要图像不可滚动,因为它们适合屏幕 - 缩略图(通过jquery隐藏/显示并隐藏主要图像,点击特定图标)。 我不能将子div(画廊)居中,因为我无法为父(页面容器)设置高度,因为我需要缩略图可滚动。但我希望主要图像集中在页面中......

这是我的HTML代码(我保留了必要的):

<!--page -->
<div id="gallery-container">

<!-- main images -->        
<div class="cycle-slideshow">
<img src="img.jpg">  
</div>

<!-- thumbnails -->
<div class="thumbs">
<img src="img.jpg">
</div>

<!-- jquery hide/show code -->
<script type="text/javascript">
$('.thumbsicon').on('click', function() {
$('.cycle-slideshow').hide(); $('.thumbs').fadeIn();
});
$('.thumbs li img').on('click', function() {
var imgSrc = $(this).attr('src');   
$('.cycle-slideshow').fadeIn('slow').css('background-image', 'url( + imgSrc + )');
$('.thumbs').hide(); 
});
</script>
</div>

和css(考虑到我的网站左边有一个250px的侧边栏菜单):

#gallery-container{width:700px;z-index:70;margin:0   auto;position:relative;overflow:hidden;padding:0 20px 0 270px;}

.cycle-slideshow {width:700px;height:517px;margin:0 auto;padding:0;position:relative;}

.thumbs {position:relative; width:700px; margin:0 auto; padding:0; display:none;}

我尝试了很多css解决方案,但似乎都没有。我能做什么?提前谢谢......

4 个答案:

答案 0 :(得分:0)

在包含您想要居中的元素的父级上,设置这些CSS属性。

显示:表细胞; 垂直对齐:中部;

答案 1 :(得分:0)

你应该在这篇文章中找到你想要的东西:http://css-tricks.com/centering-in-the-unknown/

答案 2 :(得分:0)

这是一个stackoveflow,我在一段时间后根据自己的目的调整了接受的答案代码。这是我必须定位到窗口或父元素:

Using jQuery to center a DIV on the screen

演示:http://jsfiddle.net/6P7AM/1/

jQuery.fn.center = function (centerToWindow) {
    var parent = null;
    var positionCss = null;
    if (centerToWindow) {
        parent = window;
        positionCss = "absolute";
    } else {
        parent = this.parent();
        positionCss = "relative";
    }
    this.css({
        "position": positionCss,
            "top": Math.max(0, (($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop()) + "px",
            "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
    return this;
}

$(function () {
    $(window).resize(function () {
        $("#gallery-container").center(true);
    }).trigger("resize");
});

答案 3 :(得分:0)

如果您不知道父高度,可以使用

在jQuery中获取它
var parentHeight = $('#gallery-container').height();

然后您可以在整个代码中使用parentHeight来帮助您集中精力:

var parentHeight = $('#gallery-container').height();
$('#gallery-container').css('margin-top', '-' + (parentHeight + 'px');

当然,你必须在你的css中有这个:

#gallery-container {
    position: absolute;
    top: 50%;
}

请务必在$(document).ready();上调用此居中代码,当然也可以$(window).resize();

相关问题