垂直居中div的内容(不是行高)

时间:2013-11-27 15:17:16

标签: css center

我有一个div,我需要将其内容垂直居中:

<div draggable="false" id="coffee">Free coffee for all the people who visit my restaurant</div>

#coffee {
        line-height: 235px;
        width: 300px;
    }

div {
    position: absolute;
    overflow: auto;
    text-align: left;
    font-size: 23px;
    color: rgb(26, 66, 108);
    font-family: roboto, Helvetica;
    font-style: normal;
    font-weight: bold;
    -webkit-transition: none;
    transition: none;
    left: 0px;
    top: 67.125px;
    height: 234.93749999999997px;
    opacity: 1;
}

它的工作原理是使用行高,但在跳转行中,短语过于分离,我需要将它分开。

这是小提琴链接:http://jsfiddle.net/2Mb39/4/

丹尼尔

4 个答案:

答案 0 :(得分:3)

您必须添加第二个div来实现此目的。

<div draggable="false" id="coffee" style="position: absolute; overflow: auto; text-align: left; font-size: 23px; color: rgb(26, 66, 108); font-family: roboto, Helvetica; font-style: normal; font-weight: bold; -webkit-transition: none; transition: none; left: 0px; top: 67.125px; height: 234.93749999999997px; opacity: 1;">
    <div class="inner">
    Free coffee for all the people who visit my restaurant
    </div>
</div>

#coffee {
    display: table;
    width: 300px;
    background-color: red;
}
#coffee .inner{
    vertical-align: middle;   
    display: table-cell;
}

示例:http://jsfiddle.net/2Mb39/12/

答案 1 :(得分:0)

Line-height将为para中的所有行提供垂直高度,因为你有absolute positioned div并且里面有paragraph,你需要一个子div来对齐它们垂直!

DEMO

CSS:

#coffee {
    width: 300px;
}
#coffee > .mid {
    margin-top:25%;
    text-align:center
}

<强> HTML

<div draggable="false" id="coffee" style="position: absolute; overflow: auto; text-align: left; font-size: 23px; color: rgb(26, 66, 108); font-family: roboto, Helvetica; font-style: normal; font-weight: bold; -webkit-transition: none; transition: none; left: 0px; top: 67.125px; height: 234.93749999999997px; opacity: 1;border:1px solid #000">
    <div class="mid">
    Free coffee for all the people who visit my restaurant
    </div>
</div>

答案 2 :(得分:0)

这是你想要实现的目标吗?

<强> HTML

<div draggable="false" id="coffee" style="position: absolute; overflow: auto; vertical-align: middle; font-size: 23px; color: rgb(26, 66, 108); font-family: roboto, Helvetica; font-style: normal; font-weight: bold; -webkit-transition: none; transition: none; left: 0px; top: 67px; height: 235px; opacity: 1;"><span class="marqtext">Free coffee for all the people who visit my restaurant</span></div>

<强> CSS

#coffee {
  line-height: 235px;
  width: 300px;
}
.marqtext {
  display:table-cell;
  position:relative;
  top:180px;
  text-align:center;
}

答案 3 :(得分:0)

如果您的内部div具有灵活的高度,您可以使用CSS变换将其居中:

#coffee {
    width: 300px;
    position:relative;
}
#coffee > div {
    background:#ddffff;
    position:absolute;
    top:50%;
    max-height:100%;
    -webkit-transform:translateY(-50%);
    -moz-transform:translateY(-50%);
    transform:translateY(-50%);
}

http://jsfiddle.net/2Mb39/16/