css居中的几种方式

html-css012

css居中的几种方式,第1张

1.横向居中

(1)方法一

position: fixed

/* 居中对齐begin */

left: 50%

/* 兼容老版本的方法 */

-webkit-transform: translateX(-50%)

transform: translateX(-50%)

(2)方法二

设置固定宽度,并且设置margin:auto

(3)方法三

position: fixed

left: 50% - 居中盒子宽度的50%

2.纵向居中

(1) 高度和行高设置一样

height: 100px

line-height:100px

3.横向和纵向都居中

display: flex

/* 默认的主轴是x轴row, justify-content: center 沿着主轴居中对齐 */

justify-content: center

/* 我们需要一个侧轴居中 */

align-items: center

使用CSS将字体居中可以使用HTML中的 <center>标签,简单方便。

具体介绍CSS中Center标签定义、其使用方法及相关内容:

对浏览器支持:所有浏览器都支持 <center>标签。

定义和用法:对其所包括的文本进行水平居中。

标准属性:id, class, title, style, dir, lang, xml:lang。

事件属性:onclick, ondblclick, onmousedown, onmouseup, onmouseover,

onmousemove, onmouseout, onkeypress, onkeydown, onkeyup。

HTML 与 XHTML 之间的差异:

A、在 HTML 4.01 中,center 元素不被赞成使用。

B、在 XHTML 1.0 Strict DTD 中,center 元素不被支持。

Center标签实现字体居中案例:

<table width="400" border="0">

  <tr>

    <td><center>表格内容1</center></td>

    <td>表格内容2</td>

    <td><center>表格内容3</center></td>

  </tr>

  <tr>

    <td>表格内容4</td>

    <td><center>表格内容5</center></td>

    <td>表格内容6</td>

  </tr>

  <tr>

    <td><center>表格内容7</center></td>

    <td>表格内容8</td>

    <td><center>表格内容9</center></td>

  </tr>

</table>

Center标签实现字体居中案例效果:

附,另一种实现方法:

td{ text-align:center}

<td align="center" valign="middle">

前一个是水平居中 后一个是垂直居中

对应的css写法:

<td style="text-align:centervertical-align:middle">

提示和注释:请使 CSS 样式来居中文本!