How do I vertically align a div inside a table cel

2019-04-18 02:21发布

How do I vertically center a div that is inside a table cell?

HTML:

<tr class="rowClass">
    <td class="cellClass">
        <div class="divClass">Stuff</div>
    </td>
</tr>

CSS:

.rowClass {
    vertical-align:middle !important;
    height:90px;
}

.cellClass {
    vertical-align:middle !important;
    height:90px;
}

.divClass {
    vertical-align:middle !important;
    height:90px;
}

I know the class definitions are redundant, but I've been trying lots of different things. Why isn't the solution (whatever it is) intuitive. None of the "obvious" solutions that I tried would work.

4条回答
够拽才男人
2楼-- · 2019-04-18 02:37

There is no need to defineheight in .divClass . write like this:

.cellClass {
    vertical-align:middle;
    height:90px;
    border:1px solid red;
}

Check this http://jsfiddle.net/ncrKH/

查看更多
欢心
3楼-- · 2019-04-18 02:52

.divClass { margin-top:auto; }

HTML

<table border=1>
<tr class="rowClass">
<td class="cellClass">
    <div class="divClass">Stuff</div>
</td>
</tr>
</table>

CSS

.rowClass {
vertical-align:middle !important;
height:90px;
}

.cellClass {
vertical-align:middle !important;
height:90px;
}

.divClass {
margin-top:auto; 
 }​

Live Example

查看更多
来,给爷笑一个
4楼-- · 2019-04-18 02:53

The best tutorial I have ever found regarding this question: How to vertically center stuff

查看更多
霸刀☆藐视天下
5楼-- · 2019-04-18 03:02

With out any css itself you can do this with valign="middle" try this code.

<table width="100%" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <th height="550" align="center" valign="middle" scope="col">

    <div>Hello</div>
    </th>
  </tr>
</table>
查看更多
登录 后发表回答