【问题标题】:How should i center exactly a div both vertically and horizontally?我应该如何在垂直和水平方向上准确地将 div 居中?
【发布时间】:2015-06-21 04:46:01
【问题描述】:

我是 CSS 方面的大新手,但我尝试了不同的方法,但我无法让我的 div 垂直居中。

家长:

#ModalScroll{
    position:absolute;
    top:0;
    left:0;
    z-index:1001; 
    height:1px;
    width:1px;
    overflow:hidden;
    display:none;
    font-size:100%;
    text-align:left;
}

孩子:

.ModalDialog{
    border:1px solid #3C4749;
    background-color:#FFF;
    margin:0 auto 0 auto;
    display:none;
    font-size: 12px;
    box-sizing: border-box; 
    width: 280px;
    height: 160px; 
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -80px 0 0 -140px;
}

我不知道 jQuery 中的解决方案是否应该更好,但我更喜欢 CSS 中的解决方案。

【问题讨论】:

标签: jquery html css internet-explorer centering


【解决方案1】:

您是否使用了 firebug 来确保您的 css 被充分利用? (也许其他 CSS 重载了您项目的某些属性...)

position:absolute; /*it can be fixed too*/
left:0; right:0;
top:0; bottom:0;
margin:auto;

应该做的伎俩(如Center a DIV horizontally and vertically中所说) 也许尝试在每个属性中添加“!important”...

编辑:这是带有“!important”标记的css:

position:absolute !important;
left:0 !important;
right:0 !important;
top:0 !important;
bottom:0 !important;
margin:auto !important;

【讨论】:

  • 当我检查萤火虫时,我得到了这个:i.imgur.com/HtmLTsT.png 我想删除那个黄色矩形。并将对话框放在其位置。
  • 在萤火虫的左边,你有一个“样式”块,你可以看到你的元素是什么样式。是不是“边距:自动”被剥离或其他?你在你的 HTML 中得到了一个“left”、“top”、“margin-top”,应该删除它们以获得正确的结果......你可以在删除它们时制作屏幕截图吗?
  • 我有一个 element.style 覆盖了我的 css,因为它是一个现有的应用程序。并且该对话框被许多模块使用,我怎么能覆盖它,但只是为了这个类?我不想惹其他 element.style
  • 你可以在你的CSS中添加“!important”。上面写着“不要覆盖这个属性”。因此,例如,在您的 CSS 中,输入 'margin:auto !important;' (我编辑了答案)
  • 顺便说一句,“element.style”意味着它是放在 HTML 中的属性覆盖 HTML(>),不要您是否已经掌握了 HTML 代码并删除了不需要的样式?
【解决方案2】:

这是您问题的代码,

HTML 代码:


<div class="maindiv">
    <p class="hdiv">JSFIDDLE V</p>
</div>
<br>
<div class="maindivh">
    <p class="hdih">JSFIDDLE H</p>
</div>

CSS 代码:

.maindiv {   position:relative; border:1px solid #cfcfcf; height:50px; width:200px; }

.hdiv {width:200px; text-align:center; height:50px;}

.maindivh { position:relative; border:1px solid #cfcfcf; height:150px; width:200px; }

.hdih { vertical-align:middle; display:table-cell; line-height:150px; text-align:center; width:200px; }

demo

【讨论】:

    【解决方案3】:

    试试这个:

    HTML

    <div class="divContent">
        content goes here
    </div>
    

    CSS

    .divContent {
        width: 200px;
        height: 300px;
        border: 1px solid red;
        position:absolute;
        left:0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
    }
    

    【讨论】:

    • 另一种方法:- .divContent { display: table-cell;文本对齐:居中;垂直对齐:中间 }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2011-05-18
    • 2021-06-30
    • 2020-09-16
    相关资源
    最近更新 更多