【问题标题】:Center DIV content Fluid Vertical and Horizontal居中 DIV 内容 Fluid Vertical and Horizo​​ntal
【发布时间】:2012-02-05 11:13:24
【问题描述】:

这是我的例子:

行高不适用于流体 div。我目前拥有的代码基于 line-height 但框的大小会发生变化。 那么我怎样才能让链接(内容)始终位于正中间?

我想确保此 DIV 中的内容始终从顶部和侧面居中。垂直和水平居中。

当前代码:(注意样式标签为空白,因为这是动态填充的)

    <style type="text/css">
    .box{
    width:468px; /* php changes this sometimes */
    height:60px; /* php changes this sometimes */
    background:#eee;
    text-align:
    center;
    border:
    1px solid rgb(177, 172, 171);
    line-height: 61px;
    }
    </style>

    <div style="" class="box" id="">
<a style="color:#333;font-weight:bold" href="claimPrize();">Winner!</a>
</div>

【问题讨论】:

    标签: html css xhtml margin fluid-layout


    【解决方案1】:

    不久前遇到类似的情况,搜索了一下,从css-tricks中找到了一篇关于绝对居中的文章,here 是这篇文章和随附的fiddle来测试它。

    CSS

    /* This parent can be any width and height */
    .block {
      text-align: center;
    }
    
    /* The ghost, nudged to maintain perfect centering */
    .block:before {
      content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
      margin-right: -0.25em; /* Adjusts for spacing */
    }
    
    /* The element to be centered, can
       also be of any width and height */
    .centered {
      display: inline-block;
      vertical-align: middle;
      width: 300px;
    }
    

    HTML

    <div class="block" style="height: 300px;">
    
        <div class="centered">
            <h1>Some text</h1>
            <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
        </div>
    
    </div>
    
    <div class="block" style="height: 200px;">
    
        <div class="centered">
            <h1>Some text</h1>
            <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
        </div>
    
    </div>
    
    <div class="block" style="height: 600px;">
    
        <div class="centered">
            <h1>Some text</h1>
            <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
        </div>
    
    </div>
    

    演示

    http://jsfiddle.net/andresilich/YqKMH/

    【讨论】:

    • 如何应用 Width 元素,这对旧版浏览器也有效吗?
    • @TheBlackBenzKid 由于使用了text-align:center,因此无论宽度如何,div 都将始终位于容器的中间。至于支持,由于:before:after 的伪选择器被IE7 松散地支持,我会说支持是IE8+,虽然你可能在IE7 中可以侥幸逃脱,但需要测试。我会说 IE8+ 对于非 JS 方法来说听起来很划算:P。
    • 出色的作品!一段惊人的代码。这是我需要的长期解决方案谢谢!
    猜你喜欢
    • 2012-12-20
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2017-01-12
    • 2015-11-28
    • 2018-10-24
    • 2020-01-18
    相关资源
    最近更新 更多