我尝试将文本元素在流畅的布局中居中,这意味着<div>的大小不是固定的。
我发现了一个非常好的解决方案,可以将父<div>中的子<div>水平和垂直居中,它的工作方式是:fiddle。(原文来自the second method of this post)
但是,如小提琴中所示,Large Text元素并不是垂直放置在父<div class="block">的中心,而是整个子<div class="centered">居中。
我尝试将这两个文本元素拆分为两个单独的<div>,并将只包含Large Text元素的那个放在中心。但是,当包含small text的第二个<div>被推出父<div class="block">时,它并不起作用
那么,我应该如何修改当前的居中解决方案,使Large Text元素恰好在父<div class="block">内居中,同时仍然在Large Text元素下面包含small text元素?
发布于 2012-08-21 07:42:35
vertican-align被引入到CSS中,作为表格的valign HTML属性的替代。您将注意到,display:inline-block;不会创建表单元格,也不会与vertical-align一起真正居中。如果您不太关心< IE8,您可以在父进程上使用display:table,在子进程上使用display:table-cell。
除此之外,没有快速和简单的方法来集中在父母的中心。但是,如果您知道元素的高度,则可以在div上使用旧的图像放置技巧。
<div>
    <p>Centred Text, Horizontal and Vertical</p>
</div>和CSS
div {
    positon:relative;
    text-align:center;
    height:400px;
}
div p {
    position:relative;
    display:inline-block;
    height:30px;
    margin-top:-15px;
    top:50%;
    background-color:#cccccc;
}Fiddle example
如果这对您不起作用,您也可以绝对定位文本,尽管您需要在没有父级文本对齐: center和子级<p>:inline-block辅助的情况下将其水平居中。
发布于 2012-09-22 00:24:07
如果你还在寻找这个问题的答案,我已经做了一个演示:http://dabblet.com/gist/3762377
当然,你必须给大文本(在我的演示中是‘.title’)一个固定的高度。然后使用负边距向上拉动.box,其值等于.title的高度。
标记为:
<div class="container">
    <div class="box">
        <h1 class="title">Title</h1>
        <p>Some text</p>
    </div>
</div>CSS:
.container {
    display: inline-block;      
    text-align: center;
    }
    .container:before {
        content: '';
        height: 100%;
        display: inline-block;
        vertical-align: middle;
        margin-right: -4px;
        }
    .box {
        display: inline-block;
        vertical-align: middle;
        width: 400px;
        margin-top: 70px; /* Height of .title. In this case .title's line-height. */
        }
    .title {
        display: block;
        margin: 0;
        padding: 0;     
        line-height: 70px;/* This property could be either height or top,bottom padding. */ 
        }       https://stackoverflow.com/questions/12046604
复制相似问题