将一个div居中放置在另一个div上方

3
我为我的web应用添加了一个登陆页面,所以当它从服务器加载数据时,会显示一个带有加载图像和说明的登陆页面。
  <div class="map_view">
    <!-- shown only when data is not available -->
    <div class="loading_screen">
      <img src="/img/loading_boys.gif"/>
      <h2>Connecting to the the network ...</h2>
    </div>;
  </div>
loading screen 的 div 在 div map_view 上方。我想将图像和 <h2> 居中在其父 div 上。我可以使用 text-align: center; 水平居中。但是我找不到垂直居中的方法。我还想使其兼容不同的屏幕尺寸,因此无论在哪种设备上,加载 div 都始终位于其父 div 的中心。
我尝试在 map_view 中使用 display: table; ,并在 loading_screen 上使用 display: table-cell; vertical-align: middle;,但是谷歌地图消失了,只剩下背景颜色。
2个回答

6

试试这个:

.loading_screen {
    display: flex;            /* establish flex container */
    flex-direction: column;   /* align children vertically (column format) */
    justify-content: center;  /* center children vertically */
    align-items: center;      /* center column horizontally */
}

Flexbox的优点:

  1. 代码量少,非常高效
  2. 垂直和水平居中非常简单易懂
  3. 等高列非常简单易懂
  4. 多种对齐flex元素的选项
  5. 它是响应式的
  6. 与浮动和表格不同,浮动和表格的布局能力有限,因为它们从未被用于构建布局。Flexbox是一种现代(CSS3)技术,具有广泛的选项。

请注意,Flexbox受到所有主要浏览器的支持,除了IE 8和9。一些最近的浏览器版本,如Safari 8和IE10,需要供应商前缀。要快速添加所需的所有前缀,请在此处将您的CSS发布到左侧面板:Autoprefixer


谢谢你的建议。它确实使图片和<h2>居中了。但是<h2>的内容被推到了图片的右边,我希望它在图片后面。这也导致图片水平拉伸。删除<h2>解决了上述所有问题。我想知道还有其他方法可以修复吗? - J Freebird
添加这行代码:flex-direction: column。请查看我回答中的修改后的代码块。 - Michael Benjamin
像魔法一样运作...我会研究这段代码,看看它为什么能够运行。非常感谢你的帮助! - J Freebird
很高兴能够帮助。如果您感兴趣,这是一个不错的资源:Flexbox完全指南 - Michael Benjamin

-1
使用这个技巧可以完美地在网站中居中显示内容。但需要强调的是,只有外部容器有定义的高度才能实现此效果。

请确保 .loading_screen(容器)具有固定的像素高度,然后将此 CSS 应用于 img 和 h2(内容):

.loading_screen {                                      
    height: 500px; /*for example*/                     /* Container */
}    

h2 {                                                   
    position: relative;
    top: 50%;                                          /* Content */
    transform: translateY(-50%);
}

调整转换以将元素向上或向下移动到容器中。-50%将其居中。

为了浏览器兼容性,在“transform:”上使用-moz-,-o-和-webkit-前缀:

transform: translateY();
-webkit-transform: translateY();
-o-transform: translateY();
-moz-transform: translateY();

你可以使用:
.loading_screen {
    display: flex;            
    justify-content: center;  
    align-items: center;      
    align-content: center;   
}

但是在处理多个元素堆栈时,它会产生非常尴尬和不良的影响。


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