【问题标题】:Center a div over another div将一个 div 居中在另一个 div 上
【发布时间】:2016-04-04 19:18:56
【问题描述】:

我在我的 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>

div loading screen 位于 div map_view 之上。我想将图像和&lt;h2&gt; 放在其父 div 的中心。我可以使用text-align: center; 将其水平居中。但我找不到垂直居中的方法。我也想让它兼容不同的屏幕尺寸,所以无论在什么设备上,加载 div 总是在其父 div 的中心。

我尝试在map_view 中使用display: table; 并在loading_screen 上使用display: table-cell; vertical-align: middle;,但随后谷歌地图消失了,只有背景颜色。

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    试试这个:

    .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. centering, both vertically and horizontally, is simple and easy
    3. equal height columns are simple and easy
    4. multiple options for aligning flex elements
    5. 反应灵敏
    6. 与浮动和表格不同,它们提供有限的布局容量,因为它们从未用于构建布局, flexbox 是一种现代 (CSS3) 技术,具有多种选择。

    请注意,所有主流浏览器都支持 flexbox,except IE 8 & 9。一些最新的浏览器版本,例如 Safari 8 和 IE10,需要vendor prefixes。要快速添加所需的所有前缀,请在此处的左侧面板中发布您的 CSS:Autoprefixer

    【讨论】:

    • 感谢您的建议。它确实使 img 和

      居中。但是

      内容被推到了图像的右侧,我希望它位于图像的后面。它还导致图像被水平拉伸。删除

      可以解决上述所有问题。我想知道如何以另一种方式解决它?

    • 添加这行代码:flex-direction: column。请参阅我的答案中修改后的代码块。
    • 像魔术一样工作...我将研究代码以了解其工作原理。非常感谢您的帮助!
    • 很高兴我能帮上忙。如果您有兴趣,这里是一个很好的资源:@​​987654327@
    【解决方案2】:

    使用此技巧将内容完美地集中在网站中。只是必须强调,这仅在外部容器具有定义的高度时才有效。


    确保 .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;   
    }
    

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

    【讨论】:

      猜你喜欢
      • 2013-11-30
      • 1970-01-01
      • 2013-07-08
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多