[英]Text-align: center and align-items: center not working horizontally
我以前從未遇到過這種情況。 我試過text-align: center
在各種地方,但它們都不起作用。 它們垂直工作,但不能水平工作。 我試圖讓它為每個盒子水平和垂直工作。
這是我的代碼:
.boxes { height:100%; } .box { width: 33%; height: 20%; display: -webkit-flex; } .box p { display: flex; align-items: center; } .box1 { background: magenta; } .box2 { background: cyan; } .box3 { background: yellow; } .box4 { background: orange; } .box5 { background: purple; } * { margin:0; padding:0; } html, body { height: 100%; }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="tabletest.css" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="boxes"> <div class="box box1"><p>Box 1</p></div> <div class="box box2"><p>Box 2</p></div> <div class="box box3"><p>Box 3</p></div> <div class="box box4"><p>Box 4</p></div> <div class="box box5"><p>Box 5</p></div> </div> </body> </html>
我也試圖堅持百分比來進行響應式設計。
編輯:這似乎是另一個帖子的重復,但我的問題是如何在保持框順序的同時將文本直接對齊在中心(垂直和水平)。
您可以使用 flexbox 使用此解決方案。
改變了什么?
flex-direction: column
添加到.boxes
以定義 flex 項( <p>
元素)如何放置在 flex 容器( .boxes
)中。align-items: center
以將 flex 項目沿水平軸居中。justify-content: center
使彈性項目( <p>
元素)在垂直軸上居中。 * { margin: 0; padding: 0; } html, body { height: 100%; } .boxes { height: 100%; } .box { align-items: center; display: flex; flex-direction: column; height: 20%; justify-content: center; width: 33%; } .box1 { background: magenta; } .box2 { background: cyan; } .box3 { background: yellow; } .box4 { background: orange; } .box5 { background: purple; }
<div class="boxes"> <div class="box box1"><p>Box 1</p></div> <div class="box box2"><p>Box 2</p></div> <div class="box box3"><p>Box 3</p></div> <div class="box box4"><p>Box 4</p></div> <div class="box box5"><p>Box 5</p></div> </div>
用這個:
.box p {
align-items: center;
display: block;
text-align: center;
width: 100%;
}
嘗試以下選項
.boxes {
height:100%;
}
.box {
width: 33%;
height: 20%;
}
.box p {
text-align: center;
}
.box1 {
background: magenta;
}
.box2 {
background: cyan;
}
.box3 {
background: yellow;
}
.box4 {
background: orange;
}
.box5 {
background: purple;
}
* {
margin:0;
padding:0;
}
html, body {
height: 100%;
}
注意:我使用了 align-items 的 text-align 插入
你也可以只使用這個:
.box p {
width: 100%;
display: flex;
align-items: center;
text-align: center
}
嘗試這個。
.boxes {
height:100%;
}
.box {
width: 33%;
height: 20%;
display: -webkit-flex;
position: relative;
}
.box p {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.box1 {
background: magenta;
}
.box2 {
background: cyan;
}
.box3 {
background: yellow;
}
.box4 {
background: orange;
}
.box5 {
background: purple;
}
* {
margin:0;
padding:0;
}
html, body {
height: 100%;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.