html - 垂直集中内联 block 中的内容

标签 html css

我试图让蓝色文本垂直位于行内 block div 的中心。我尝试了各种变体,但无济于事。父级必须保留为内联 block 。

如果父级显示为 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>

最佳答案

将此属性添加到 .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>

关于html - 垂直集中内联 block 中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401002/

相关文章:

Java返回字符串撇号并返回不按我想要的方式工作

html - 构建大型基于 html 的元素的最佳实践

javascript - 如何限制JQuery selectable-helper的范围?

html - Ruby on Rails ajax 弹出消息

html - 如何将搜索栏移动到导航栏旁边

html - 拉伸(stretch)图像以适应特定的 div

javascript - 使用 PHP 在网站内模拟分辨率

html - asp.net 调用 "target"伪 css 类

javascript - 尝试上传 shapefile 时出现 dom 未定义错误

html - CSS 扩展文本超链接及其下划线之间的空间