我試圖找到垂直居中文本,但我找不到滿意的答案。我發現的最好的答案是this。這使得它看起來像允許我垂直居中文本,但是如果我使用它並添加更多文本,它只會擴展到底部,而不是重新居中,如水平發生的情況。我如何垂直居中文本與css
請注意,我正在尋找一個CSS唯一的解決方案,所以沒有JavaScript請。 請注意,我希望能夠添加多行文字。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
div#maindiv {
width: 810px;
height: 99px;
background-color: black;
margin: 0px;
padding: 0px;
color: white;
font-family: Sans-serif;
text-align: center;
display: table;
}
div#maindiv span {
font-size: 1.1em;
}
div#part1 {
width: 270px;
height: 99px;
background-color: #6DCAF2;
float: left;
vertical-align: middle;
position: relative;
}
div#horizon1 {
background-color: green;
height: 1px;
left: 0;
overflow: visible;
position: absolute;
text-align: center;
top: 50%;
visibility: visible;
width: 100%;
}
div#content1 {
background-color:green;
height:99px;
width: 270px;
position: absolute;
top: -50px;
}
</style>
<title>XHTML-Strict</title>
</head>
<div id="maindiv">
<body>
<div id="part1">
<div id="horizon1">
<div id="content1">
<div id="bodytext1">
<span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dolor augue, faucibus quis sagittis
<span>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
最後,我想要有3個塊,每個塊都將文本居中放在中間。這些文本由客戶編輯,因此它們必須能夠跨越多行。目前,文本從文本框的頂部開始到底部,最後,我希望文本從某個點開始,以便文本正文的中心位於文本框的中心。
我的最終解決方案 注意:如果您在同一個div中有float:left,則vertical-align不起作用。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
div#maindiv {
width: 810px;
height: 99px;
background-color: black;
margin: 0px;
padding: 0px;
color: white;
font-family: Sans-serif;
}
div#maindiv span {
font-size: 1.1em;
}
div.part {
width: 262px;
height: 99px;
padding: 0px;
margin: 0px;
padding: 4px;
border: 0px;
color: white;
text-align: center;
display: table-cell;
vertical-align: middle;
}
div.bgc1 {
background-color: #6DCAF2;
}
div.bgc2 {
background-color: #2A4B9A;
}
div.bgc3 {
background-color: #FF8A00;
}
</style>
<title>XHTML-Strict</title>
</head>
<div id="maindiv">
<body>
<div style="float: left;">
<div class="part bgc1">
<span>
Vegeta! What does the scouter say about his power level?!
</span>
</div>
</div>
<div style="float:left;">
<div class="part bgc2">
<span>
It's over NINE THOUSAAAAAAAAAND!
</span>
</div>
</div>
<div style="float:left;">
<div class="part bgc3">
<span>
What NINE THOUSAND? There is no way that can be right!
</span>
</div>
</div>
</div>
</body>
</html>
您可以發佈您當前的代碼?第一個問題總是:'你希望中心的文字在哪裏?' – ptriek 2012-01-03 15:18:45
有多種方法可供使用:http://www.vanseodesign.com/css/vertical-centering/如果您可以分享您使用的代碼,也許我們可以幫助您制定特定的解決方案。 – 2012-01-03 15:19:27
其他的css方式是將文本放在表格單元格中;否則你將不得不使用js – mreq 2012-01-03 15:19:44