html - 无法使用显示 :table 使 div 居中对齐

标签 html css

我正在使用显示表格和表格单元格垂直对齐中间使 div 居中对齐。但是中心 div 没有定位在中心。

fiddle :Here

CSS:

.landing-right {
    position: relative;
    padding: 50px 0px;
    float: left;
    display: table;
    width: 365px;
    height: 100%;
    margin-left: -70px;
}
.landing-img {
    height: 420px;
    position: relative;
    float: left;
    width: 100%;
    background-repeat: no-repeat;
    border: 15px solid #fff;
    display: table-cell;
    vertical-align: middle;
}

HTML:

<div class="landing-right">
            <div class="landing-img" style="background-image: url(&quot;https://cdn.filestackcontent.com/Cvj2tN3S7ikTu981vJVp&quot;);">                
</div>

最佳答案

.landing-right 有几个问题:

  • 它有 float: left。如果需要水平居中,则不应定义此CSS规则。
  • 它有 margin-left: -70px 这使得它向左偏移了 70px。这不是必需的,如果元素需要水平居中,则应将其删除。
  • 没有定义 CSS 规则来水平居中元素,实现它的最简单方法是使用 margin: 0 auto

对于垂直居中,代码运行良好。

这是一个代码片段,它使图像在您的案例中水平和垂直居中:

.landing-main {
    position: relative;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    background: #fefefe;
}
.landing-right {
    position: relative;
    padding: 50px 0px;
    display: table;
    width: 365px;
    height: 100%;
    margin: 0 auto;
}
.landing-img {
    height: 420px;
    position: relative;
    float: left;
    width: 100%;
    background-repeat: no-repeat;
    border: 15px solid #fff;
    display: table-cell;
    vertical-align: middle;
}
.landing-inner {
    width: 100%;
    box-shadow: 0 2px 9px 2px rgba(0,0,0,0.4);
    padding: 40px 0px;
    min-height: 100vh;
    background: #f8f8f8;
}
<div class="landing-main">

<div class="landing-inner">
<div class="landing-right">
            <div class="landing-img" style="background-image: url(&quot;https://cdn.filestackcontent.com/Cvj2tN3S7ikTu981vJVp&quot;);">
            
            </div>
        </div>
        </div></div>

关于html - 无法使用显示 :table 使 div 居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44082987/

相关文章:

css - 是否有提供下拉菜单和列表框组合的 Bootstrap 插件?

html - CSS 最小化器?

javascript - 在我的 html 页面的每个 div 中更改 Logo

html - CSS - 以相对于其最大宽度的 % 设置跨度的宽度

css - iphone 粘性菜单 jquery onscroll ios 9

javascript - 如何在通过 XMLHttpRequest 上传文件时获得进度

在 sencha touch 应用程序中应用 "Application Error : connection to the server was unsuccessful"修复程序后,Android 后退按钮操作问题

jquery - 如何强制删除所有媒体查询并只坚持一种尺寸

css - 从中心显示背景图像

javascript - Cordova/Phonegap 3.1 键盘(仍然)覆盖聚焦的表单字段 - iOS 7