Vertically center content of floating div

不羁的心 提交于 2019-11-28 06:24:05
Systembolaget

The others are right, you need to nest two DOM elements which gives you more options controlling the centering. Here's the code:

.floating {
  display: table;
  float: right;
  height: 200px;
  width: 400px;
  border: 1px solid red;
}
.floating p {
  display: table-cell; 
  vertical-align: middle; 
  text-align: center;
}
<div class="floating">
    <p>This is the proper way that validates and breaks across multiple
    lines, if the text is longer than just a few words and still
    should be vertically centered. Here, it's also horizontally
    centered for added joy.</p>
</div>

Add the text inside a <p>.

HTML

<div class="floating">
    <p>This should be in the middle</p>
</div>

CSS

.floating {
    height: 100px;
    border: 1px solid #f00;
    display: table-cell;
    vertical-align: middle;
}
​

If you know the height, then

line-height:100px;

If not, use javascript to set line-height after rendering.

http://jsfiddle.net/DeH6E/4/

I was also looking for a solution to this and eventually came up with this:

http://jsfiddle.net/w6j9mgjp/1/

.floating {
    height: 100px;
    float: left;
    border: 1px solid red;
}

.floating::before {
    content: "a";
    display: block;
    visibility: hidden;
    height: 50%;
    margin-top: -.7em;
}

it only works for a single line of text, though.

http://jsfiddle.net/DeH6E/2/

the text inside of your div needs to be in its own div tag, and that div tag needs to be set to display:table-cell; and vertical-align:middle; while your .floating div needs to be set as display:table;

or you can set a p tag or some other sort of formatting tag in there to contain your text, eg span, or p

Just play with the pseudo selector.

.floating {
    height: 100px;
    float: left;
    border: 1px solid red;
}

.floating::before {
    content: '';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!