【发布时间】:2019-04-02 02:58:20
【问题描述】:
我正在尝试创建一个横幅/标题,它将在主 div 后面有一条线。我希望标题的行和文本位于中间(垂直),如图所示:
问题是如果我改变浏览器的大小,hr 和文本没有对齐(垂直)。以下是第一个版本:
.section {
clear: both;
padding: 0px;
margin: 0px;
}
.col {
text-align:center;
display: block;
float:left;
margin: 1% 0 1% 0%;
}
.col:first-child { margin-left: 0; }
.group:before,
.group:after { content:""; display:table; }
.group:after { clear:both;}
.group { zoom:1; /* For IE 6/7 */ }
.span_3_of_3 { width: 100%; }
.span_2_of_3 { width: 66.66%; }
.span_1_of_3 { width: 33.33%; }
@media only screen and (max-width: 480px) {
.col { margin: 1% 0 1% 0%; }
.span_3_of_3, .span_2_of_3, .span_1_of_3 { width: 100%; }
}
#middle
{
background:#CCC;
color:#FC3699;
height:100px;
margin-top:0;
line-height:100px;
}
hr {
margin-top:40px;
border:2px solid #FC3699;
}
<div class="section group">
<div class="col span_1_of_3">
<div class="topsection">
<div class="header"><hr /></div>
</div>
</div>
<div id="middle" class="col span_1_of_3">
aaaaaaa
</div>
<div class="col span_1_of_3">
<div class="topsection">
<div class="header"><hr /></div>
</div>
</div>
</div>
这是第二个版本。我可以使用下面的 sn-p 代替 3 列。问题出在这一行:
高度:100px; 行高:100px;
我希望高度为 100%。但是行高不能:
.main {
height:100%;
min-height:100px;
display: block;
text-align: center;
overflow: hidden;
white-space: nowrap;
}
.main > span {
width:200px;
height:100px;
line-height: 100px;
background:#F1F1F1;
position: relative;
display: inline-block;
}
.main > span:before,
.main > span:after {
content: "";
position: absolute;
top: 50%;
width: 9999px;
height: 3px;
background: #FC3699;
}
.main > span:before {
right: 100%;
margin-right: 15px;
}
.main > span:after {
left: 100%;
margin-left: 15px;
}
<div class="main">
<span style="vertical-align: middle;">Text</span>
</div>
这是第三个也是最好的版本,我只需要text-aling:center; 文本。但即使我在 CSS 中添加它,它也不起作用是有原因的:
.main {
height:100%;
min-height:100px;
display: block;
text-align: center;
overflow: hidden;
white-space: nowrap;
}
.main > span {
width:200px;
height:100px;
line-height: 100px;
background:#F1F1F1;
position: relative;
display: inline-block;
}
.main > span:before,
.main > span:after {
content: "";
position: absolute;
top: 50%;
width: 9999px;
height: 3px;
background: #FC3699;
}
.main > span:before {
right: 100%;
}
.main > span:after {
left: 100%;
}
#child {
display: table-cell;
vertical-align: middle;
}
<div class="main">
<span><div id="child">Text</div></span>
</div>
【问题讨论】:
-
有很多方法可以实现这一点。您已经在第二个版本中使用 :before 和 :after 完成了此操作。试试这个 #child { display: table-cell;vertical-align: middle;宽度:继承;}。
-
@Amit1992 我对 CSS 有一些限制。第一个答案很好用:D 谢谢大家
标签: html css vertical-alignment