怎么在CSS中實現居中布局?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
css是一種用來表現HTML或XML等文件樣式的計算機語言,主要是用來設計網頁的樣式,使網頁更加美化。它也是一種定義樣式結構如字體、顏色、位置等的語言,并且css樣式可以直接存儲于HTML網頁或者單獨的樣式單文件中,而樣式規則的優先級由css根據這個層次結構決定,從而實現級聯效果,發展至今,css不僅能裝飾網頁,也可以配合各種腳本對于網頁進行格式化。
1. 父級容器設置成表格,子級設為行內元素。
適合子級內容為文本展示。

<!-- css -->
<style>
#parent {
height: 200px;
width: 200px;
border: 1px solid red;
display: table-cell; /* 轉變成表格 */
text-align: center; /* 水平 */
vertical-align: middle; /* 垂直 */
}
#child {
background-color: blue;
color: white;
display: inline; /* 子元素設置為行內或行內塊 */
}
</style>
<!-- html -->
<div id="parent">
<div id="child">內容</div>
</div>2. 父級容器設置相對定位,子級設置絕對定位后通過外邊距居中。

<!-- css -->
<style>
#parent {
height: 200px;
width: 200px;
border: 1px solid red;
position: relative; /* 設置相對定位 */
}
#child {
height: 50px;
width: 50px;
color: white;
background-color: blue;
/* 絕對定位,4 個方向設置為 0 后,margin 設為 auto */
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<!-- html -->
<div id="parent">
<div id="child"></div>
</div>3. 父級容器設置為彈性盒,子級設置外邊距。

<!-- css -->
<style>
#parent {
height: 200px;
width: 200px;
border: 1px solid red;
display: flex; /* 父元素轉換為彈性盒 */
display: -webkit-flex; /* Safari */
}
#child {
height: 50px;
width: 50px;
background-color: blue;
margin: auto;
}
</style>
<!-- html -->
<div id="parent">
<div id="child"></div>
</div>4. 父級容器設置相對定位,子級設置絕對定位,左邊距和上邊距設置負一半寬度。
適合子級的寬高固定的情況。

<!-- css -->
<style>
#parent {
height: 200px;
width: 200px;
border: 1px solid red;
position: relative; /* 設置相對定位 */
}
#child { /* 子元素已知自身寬高的情況下 */
background-color: blue;
width: 50px;
height: 50px;
margin-top: -25px;
margin-left: -25px;
position: absolute;
left: 50%;
top: 50%;
}
</style>
<!-- html -->
<div id="parent">
<div id="child"></div>
</div>5. 父級容器設置相對定位,子級設置絕對定位,通過變形屬性設置水平和垂直方向負一半。
適合子級的寬高不固定的情況。

<!-- css -->
<style>
#parent {
height: 200px;
width: 200px;
border: 1px solid red;
position: relative; /* 設置相對定位 */
}
#child { /* 子元素未知自己的寬高,使用 transform 的 translate */
border: 1px solid blue;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
</style>
<!-- html -->
<div id="parent">
<div id="child">
<div id="content">
內容1
<br/>
內容2
</div>
</div>
</div>6. 父級設置為彈性盒,設置對齊屬性。

<!-- css -->
<style>
#parent {
height: 200px;
width: 200px;
border: 1px solid red;
display: flex; /* 父元素轉換為彈性盒 */
display: -webkit-flex; /* Safari */
justify-content: center;/* 水平 */
align-items: center; /* 垂直 */
}
#child {
height: 50px;
width: 50px;
background-color: blue;
}
</style>
<!-- html -->
<div id="parent">
<div id="child"></div>
</div>看完上述內容,你們掌握怎么在CSS中實現居中布局的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。