我正在尝试将蓝色文本垂直放在内联块div
的中心。我尝试了各种变化但无济于事。父级必须保留为内联块。
如果父项显示为table
,子项显示为vertical-align: middle
的表格单元格,那么它几乎可以正常工作,但是失败,因为子div是100%高,我想添加一个border-top
和底部约有10px
填充,不能在100%高度下工作。无法使用display: flex
,因为它会破坏其他元素的定位。线高也失败。
有人可以解释这里的问题因为我很困惑。
.matches-container {
padding-top: 50px;
}
.match {
width: 25%;
height: 250px;
display: inline-block;
border: 1px solid yellow;
}
.match-contents {
background: blue;
border-top: 1px solid red;
border-bottom: 1px solid red;
}
.a {
background: black
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<section class="matches-container">
<article class="match a">
<div class="match-contents">central text with borders top and bottom</div>
</article>
<!-- -->
<article class="match b">
<div class="match-contents">central text with borders top and bottom</div>
</article>
</section>
答案 0 :(得分:3)
在.match-contents
.match-contents {
position:relative;
top:50%;
transform:translateY(-50%);
}
您的代码按预期工作...否则您添加了一个属性以使蓝框垂直居中。
这是片段。
.matches-container {
padding-top: 50px;
}
.match {
width: 25%;
height: 250px;
display: inline-block;
border: 1px solid yellow;
}
.match-contents {
background: blue;
border-top: 1px solid red;
border-bottom: 1px solid red;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.a {
background: black
}
<section class="matches-container">
<article class="match a">
<div class="match-contents">central text with borders top and bottom</div>
</article>
<!--
-->
<article class="match b">
<div class="match-contents">central text with borders top and bottom</div>
</article>
</section>
答案 1 :(得分:1)
您可以在此处使用display: inline-flex
和align-items: center
。演示:
.matches-container {
padding-top: 50px;
}
.match {
width: 25%;
height: 250px;
/* become inline flex-container */
display: inline-flex;
/* center items */
align-items: center;
border: 1px solid yellow;
}
.match-contents {
background: blue;
border-top: 1px solid red;
border-bottom: 1px solid red;
}
.a {
background: black
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<section class="matches-container">
<article class="match a">
<div class="match-contents">central text with borders top and bottom</div>
</article>
<!-- -->
<article class="match b">
<div class="match-contents">central text with borders top and bottom</div>
</article>
</section>