html - 您如何在绝对 div 中将绝对 div 居中?

标签 html css

这是 jsfiddle:http://jsfiddle.net/techsin/1o5zzcgh/

我想在不使用 jquery 的情况下将两个绝对定位的 div 居中。现在我正在使用 top:0 和 bottom 0,但是当定义了高度时,这不起作用。

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

最佳答案

你可以使用这个小技巧:

HTML:

    <div class="out">
    <div class="in">
    </div>
</div>

CSS:

.in, .out {
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
}
.in {
   background-color: red;
   height: 50%;
   left: 50%;
   top: 50%;
   -moz-transform: translate(-50%, -50%);
   -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
     -webkit-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);  
}
.out {
  background-color: blue;
}

通过使用 left/top 和 translate minus values,您可以根据需要居中。

HTH.

关于html - 您如何在绝对 div 中将绝对 div 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187039/

相关文章:

html - 如何让 flex 元素中的元素拉伸(stretch) 100% 的父项?

html - 大量的 IFRAME 会影响性能吗?

css - 为什么在我的 Angular 应用程序加载时没有立即应用预期的 Material 按钮样式,而是稍后才应用?

css - 子 div 超出父 div

html - 如何使用 Bootstrap 让一列跨越多行?

html - 禁用显示或替换特定 div 的内容

css - html 视频不会在谷歌浏览器上播放,但会在 firefox 上播放但不同

无论操作系统如何,都可以使用的 HTML 字体?

html - CSS 导航菜单中的事件页面带有 MVC3 中悬停效果的背景图像

html - 造型营业时间