水平居中
- 若是行內元素, 給其父元素設置 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:0;right:0;margin: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-cell;vertical-align:middle;
- 用 Flex 佈局
css
.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; }