html - 位置为 :absolute not centering inside parent div with position:relative 的图像

标签 html css twitter-bootstrap

首先,不确定它是否相关,但我使用的是 Bootstrap 3。

因此,对于我页面的这一部分(下面还有更多内容),我将视口(viewport)高度设置为 100,其中两行各占该视口(viewport)的 50%。第一行是我试图在水平和垂直方向居中的图像。第二行是我试图水平居中并固定在底部的图像。 html 看起来像这样:

<div class='row vh-100'>
    <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 height-100'>

        <!-- tats -->
        <div class='row height-50'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 relative height-100'>
                <img src='images/logo.png' 
                     class='img-responsive block absolute center middle max-height-100'>
            </div>
        </div>

        <!-- silhouette -->
        <div class='row height-50'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 relative height-100'>
                <img src='images/silhouette.png' 
                     class='img-responsive block absolute center bottom max-height-100'>
            </div>
        </div>

    </div>
</div>

CSS 看起来像这样:

.block{
	display: block;
}

.absolute{
	position: absolute;
}

.relative{
	position: relative;
}

.vh-100{
	height: 100vh;
}

.vh-50{
	height: 50vh;
}

.height-100{
	height: 100%;
}

.height-50{
	height: 50%;
}

.center{
    margin-left: auto;
    margin-right: auto;
}

.top{
	top: 0%;
}

.middle{
	top: 50%;
}

.bottom{
	bottom: 0%;
}

.max-height-100{
	max-height: 100%;
}

所以我遇到的是这样的:图像不会水平居中,除非我将它们的位置更改为相对位置。此外,第一张图片在整个页面内垂直居中,而不是其包含的 div。有什么想法吗?

最佳答案

绝对位置元素是这样居中的:

#element {
 left:50%;
 top:50%;
 transform:translate(-50%,-50%);
}

(不要忘记为转换添加供应商:-webkit-transform 等)

另外,如果你知道绝对元素的宽度,你可以使用:

margin-left:-halfelemwidth;
margin-top:-halfelemheight;

这将有助于支持不支持 css 转换的旧浏览器

编辑:打字时太累了,下面的用户提醒我注意 margin-top 和 margin-left 应该是一半而不是全。

edit2:您也可以尝试这种方法。

对于具有高度的父级元素,使用:

display:table-cell;
vertical-align:middle;
text-align:center;

这可以在不离开容器的情况下使图像居中,并且没有相对和绝对元素。

关于html - 位置为 :absolute not centering inside parent div with position:relative 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26318059/

相关文章:

javascript - 停止和启动页面溢出/单击时滚动的能力

javascript - Bootstrap-根据宽度调整元素的高度

javascript - 首次尝试 Bootstrap 模式后,计数器值无法正常工作

html - 制作 DHTMLEd 控件的代码用弯引号替换直引号

javascript - 将 div 设置为位置 : fixed on scroll with jquery causes content below to jump up

html - 当我将鼠标悬停在第二个 <DIV> 上时,如何使一个 <DIV> 在第二个 <DIV> 下方可见

javascript - jQuery.load()、jQuery.focus() 和链接标记之间的冲突

PHP 将单选按钮和复选框值链接到连接表?

javascript - 在 Angular 的 innerHTML 中使用字符串插值

CSS:带有透明 div 部分的不透明叠加层