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

  • 本文关键字:垂直居中 div 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/

Daniel

您必须添加第二个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/

这就是您想要实现的目标吗?

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;
}

如果您的内部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/

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

演示

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>

最新更新