新聞中心
一、居中

1. 居中對齊元素
將塊元素水平居中對齊(像
然后元素將占用指定的寬度,剩下的空間將平分在兩個邊距之間:
這個div是居中的。
- .center {
- margin: auto;
- width: 50%;
- border: 3px solid green;
- padding: 10px;
- }
注意:如果沒有設置寬度屬性,則居中對齊沒有效果 (或者設置到100%).
2. 居中對齊文本
將元素內(nèi)部的文本居中, 使用text-align: center;
這些文本是居中的。
- .center {
- text-align: center;
- border: 3px solid green;
- }
3. 居中圖片
居中圖片, 使用 margin: auto; 并且設置為塊級元素:
- img {
- display: block;
- margin: auto;
- width: 40%;
- }
二、左右
HTML代碼:
編程字典 右對齊
如何正確定位元素與位置屬性的一個例子:
在我年輕而脆弱的歲月里,父親給了我一些我一直以來一直在思考的建議.
1. 左右對齊 - 使用 position
對齊元素的一種方法是使用 position: absolute;
在我年輕而脆弱的歲月里,父親給了我一些我一直以來一直在思考的建議。
- .right {
- position: absolute;
- right: 0px;
- width: 300px;
- border: 3px solid #73AD21;
- padding: 10px;
- }
注意:
絕對定位元素從正常流中移除,并且可以重疊元素。
當使用 position對齊元素時, 總是定義 margin 和 padding 為 元素. 這是為了避免不同瀏覽器的視覺差異。
還有IE8和早期版本有一些問題, 當使用 position. 如果容器元素有一個指定的寬度 (例如:
- body {
- margin: 0;
- padding: 0;
- }
- .container {
- position: relative;
- width: 100%;
- }
- .right {
- position: absolute;
- right: 0px;
- width: 300px;
- background-color: #b0e0e6;
- }
2. 左右對齊 - 使用 float
對齊元素的另一種方法是使用 float 屬性:
- .right {
- float: right;
- width: 300px;
- border: 3px solid #73AD21;
- padding: 10px;
- }
提示:
當將元素使用浮動對齊時,總是為body元素定義邊距和填充。這是為了避免不同瀏覽器的視覺差異。
- body {
- margin: 0;
- padding: 0;
- }
- .right {
- float: right;
- width: 300px;
- background-color: #b0e0e6;
- }
效果圖:
三、垂直居中,水平居中
HTML代碼:
編程字典 居中
在這個實例中,
- 我們使用定位和transform屬性實現(xiàn)元素的水平和垂直居中:
我水平垂直居中.
注意: transform屬性不支持IE8和更早的版本.
1. 使用 padding
有許多方法來中心垂直CSS元素. 一個簡單的解決方案是使用頂部和底部 padding:
- .center {
- padding: 70px 0;
- border: 3px solid green;
- }
水平和垂直居中, 使用 padding 和 text-align: center:
垂直居中
- .center {
- padding: 70px 0;
- border: 3px solid green;
- text-align: center;
- }
2. 使用 line-height
另一個技巧是使用 line-height 屬性值等于 height 屬性值.
- .center {
- line-height: 200px;
- height: 200px;
- border: 3px solid green;
- text-align: center;
- }
- /* If the text has multiple lines, add the following: */
- .center p {
- line-height: 1.5;
- display: inline-block;
- vertical-align: middle;
- }
3. 使用 position & transform
如果padding和line-height不可選,第三種解決方案是使用定位和變換屬性:
- .center {
- height: 200px;
- position: relative;
- border: 3px solid green;
- }
- .center p {
- margin: 0;
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- }
四、總結
本文基于Html基礎,主要介紹了Html中對齊的方式,對于對齊中的標簽做了詳細的講解,用豐富的案例 ,代碼效果圖的展示,幫助大家更好理解 。
最后,希望可以幫助大家更好的學習CSS3。
文章題目:一篇文章帶你了解CSS對齊方式
標題來源:http://www.dlmjj.cn/article/dhehcej.html


咨詢
建站咨詢
