Elaine's Blog 朝著 senior 前進的工程師

CSS 置中

2017-03-17
CSS

div 置中

如果是這種 block 元素的話,置中方法就要用 margin:0px auto

<div style="background-color:gray;width:420px;height:120px;padding:10px">
  <div style="background-color:yellow;width:200px;height:80px;"></div>
</div>

<div style="background-color:gray;width:420px;height:120px;padding:10px">
  <div
    style="background-color:yellow;width:200px;height:80px;margin:0 auto;"
  ></div>
</div>

table 的文字、圖片置中

水平置中

利用 align="center"

<table width="300" height="80" border="1">
  <tr>
    <td align="center">HTML 水平置中</td>
  </tr>
</table>

垂直置中

利用 valign="center"

<table width="300" height="80" border="1">
  <tr>
    <td valign="center">HTML 垂直置中</td>
  </tr>
</table>

文字置中

水平置中

  • text-align:center
  • 其他
    • text-align:left; //向左對齊
    • text-align:right; //向右對齊
    • text-align:center; //置中
    • text-align:justify; //使左右對齊本文
    • text-align:inherit; //繼承父元素的 text-align 屬性
<div style="text-align:center;background-color:pink;width:200px;height:60px">
  這裡是文字
</div>

垂直置中

利用 line-height 設為 height 就可以垂直置中了

<div
  style="background-color:#C7FF91;width:300px;height:100px;text-align:center;line-height:100px;"
>
  測試文字垂直置中
</div>

好用的工具

如果上面你都看不懂的話沒關係,你可以利用下面的網站 HOW TO CENTER IN CSS

參考資料


上一篇 CSS Display 屬性

Content