【问题标题】:Best ways of centralising a div inside another div [duplicate]将 div 集中在另一个 div 中的最佳方法 [重复]
【发布时间】:2017-07-10 01:09:34
【问题描述】:

我只是好奇在另一个 div 中居中(垂直和水平)对齐 div 的最佳方法是什么。这个例子有一个红色的 div,我想用背景图片在 div 内垂直和水平居中。

这样做的最佳方法是什么,以便在调整浏览器窗口大小和在手机上显示时自动适应?

以下方法失败:

  • 位置:相对; & 最高:50%; - 只有最顶部的 div 是集中的,而不是其余的。添加负边距顶部失败,因为它将其应用于父元素
  • 保证金:25% 自动;
  • 垂直对齐:中间;
  • 对齐内容:居中; - 大概只适用于弹性盒

代码如下:

body{
    background: yellow;
    margin: 0 auto;
}

#first{
    width:100%;
    height:550px;
    background: url('https://static.pexels.com/photos/30627/pexels-photo-30627.jpg');
    background-size: cover;
}

#central{
    width:200px;
    height:100px;
    background: red;
    margin: 0 auto;
    
    /*
    
    Why DO THESE FAIL:
    
    position:relative; & top: 50%;
    
    margin: 25% auto;
    
    vertical-align: middle;
    
    justify-content: center; - presumably only applies to flexboxes
    
    */
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="css.css">
    <title>title</title>
  </head>
  <body>
      
      <div id="first">
        <div id="central"></div>
      </div>
  
  </body>
</html>

感谢您的帮助。

【问题讨论】:

标签: html css


【解决方案1】:

我认为最好的方法是使用 flexbox。检查这个惊人的post about flexbox

父 div 的 css 必须是这样的:

.first {
  display: flex;
  align-items: center;
}

【讨论】:

    猜你喜欢
    • 2016-07-20
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2013-03-03
    • 2016-03-18
    相关资源
    最近更新 更多