css怎么设置居中

html-css020

css怎么设置居中,第1张

水平居中

若是行内元素, 给其父元素设置 text-align:center,即可实现行内元素水平居中.

若是块级元素, 该元素设置 margin:0 auto即可.

若子元素包含 float:left 属性, 为了让子元素水平居中, 则可让父元素宽度设置为fit-content,并且配合margin, 作如下设置:

.parent{

width: -moz-fit-content

width: -webkit-fit-content

width:fit-content

margin:0 auto}

使用flex 布局, 可以轻松的实现水平居中, 子元素设置如下:

.son{

display: flex

justify-content: center}

使用CSS3中新增的transform属性, 子元素设置如下:

.son{

position:absolute

left:50%

transform:translate(-50%,0)}

使用绝对定位方式, 以及负值的margin-left, 子元素设置如下:

.son{

position:absolute

width:固定

left:50%

margin-left:-0.5宽度}

使用绝对定位方式, 以及left:0right:0margin:0 auto子元素设置如下:

.son{

position:absolute

width:固定

left:0

right:0

margin:0 auto}

垂直居中

若元素是单行文本, 则可设置 line-height 等于父元素高度

若元素是行内块级元素, 基本思想是使用display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央.

.parent::after, .son{

display:inline-block

vertical-align:middle}.parent::after{

content:''

height:100%}

元素高度不定

可用 vertical-align 属性, 而vertical-align只有在父层为 td 或者 th 时, 才会生效, 对于其他块级元素, 例如 div、p 等, 默认情况是不支持的. 为了使用vertical-align, 我们需要设置父元素display:table, 子元素 display:table-cellvertical-align:middle

用 Flex 布局

.parent {

display: flex

align-items: center}

可用 transform , 设置父元素相对定位(position:relative), 子元素如下css样式:

.son{

position:absolute

top:50%

-webkit-transform: translate(-50%,-50%)

-ms-transform: translate(-50%,-50%)

transform: translate(-50%,-50%)}

元素高度固定

设置父元素相对定位(position:relative), 子元素如下css样式:

.son{

position:absolute

top:50%

height:固定

margin-top:-0.5高度}

设置父元素相对定位(position:relative), 子元素如下css样式:

.son{

position:absolute

height:固定

top:0

bottom:0

margin:auto 0}

1.文字居中定义

文字居中始终是要的,所以首先给予ul外层div一个text-align(文本对齐:居中),还可以给一个“溢位:隐藏(overflow: hidden)”,当然也可以定义一下高和宽。

2.ul定义

ul不能定义宽度,我们只能给一个定位,类型为相对(position: relative),置入左为50%(left: 50%),当然也可以给一个浮动。请注意,ul千万不能用溢位:隐藏(overflow: hidden),这样,部分li就无法显示。

3.li定义

li的定义跟ul差不多,宽度不固定,同样给一个定位,类型为相对(position: relative),置入右为50%(right: 50%),恰恰和ul相反,这样定义后li就可以无论分页多少始终居中了。

需要表格水平居中只要给它加个style="margin:0 auto"样式就可以了

例:

<table width="200" height="300" border="0" cellspacing="0" cellpadding="0" style="margin:0 auto">

<tr>

<td bgcolor="#FF0000"> </td>

</tr>

</table>

需要表格在页面上下左右都居中需要定位

例:

<style type="text/css">

.tab{ position:fixed_position:absolutetop:50%left:50%margin-top:-150px/*表格高的一半*/ margin-left:-100px/*表格宽的一半*/}

</style>

<table width="200" height="300" border="0" cellspacing="0" cellpadding="0" class="tab">

<tr>

<td bgcolor="#FF0000"> </td>

</tr>

</table>