html - Flexbox CSS 垂直对齐不完全居中

标签 html css flexbox

我之前使用 flexbox 进行垂直对齐,但对于我现在使用它的元素,对齐非常偏离中心,特别是对于下面 JSFiddle 示例中的 div,其中添加了一个按钮到包含其余文本的同一个 div 使对齐方式太低。

代码:

#servicesGrid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.service {
  width: 24.85%;
  height: 45%;
  background: #262626;
  display: block;
  float: left;
  margin: 0 0.2% 0 0;
  text-align: center;
}
#servicesGrid .service:nth-of-type(1) {
  width: 100%;
  margin: 0 0 0.2% 0;
  height: 80%;
}
#servicesGrid .service:nth-of-type(5) {
  margin-right: 0;
}
.serviceContent {
  margin: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  color: #fff;
  text-align: center;
}
.button {
  color: #fff;
  border: 2px solid #fff;
  border-radius: 15px;
  padding: 10px 20px 10px 20px;
  text-transform: uppercase;
  font-family: 'Effra-Regular';
  text-decoration: none;
  transition: all linear 0.3s;
  -webkit-transition: all linear 0.3s;
  -moz-transition: all linear 0.3s;
}
.button:hover {
  color: #000;
  background: #fff;
}
<div id="servicesGrid">
  <div class="service">
    <div class="serviceContent">
      <div style="margin-left:auto; margin-right:auto">
        <h1 style="font-size:40px; font-family:'Effra-Light'; margin-bottom:-10px">Service</h1>
        <h4>Lorem ipsum dolor sit amet</h4>
        <br/>
        <a href="#contactUs" class="button" alt="Find Out More Button">Find Out More</a>
      </div>
    </div>
  </div>
</div>

JSFiddle:https://jsfiddle.net/f92udw9v/2/ .

最佳答案

你有几个问题:

  1. 额外的填充和边距(您的按钮在 .serviceContent 之外运行)。

  2. 顶部的 H1 有一个 margin-top/bottom(可能是用户代理值),它与 .serviceContent 的顶部保持一定距离。

看看 changes I made to your jsfiddle .

          <div style="margin-left:auto; margin-right:auto;border: 1px solid yellow;"> 

            <h1 style="font-size:40px; font-family:'Effra-Light';margin-top: 0px;">Service</h1>

            <h4>Lorem ipsum dolor sit amet</h4>

            </br>

            <a href="#contactUs" class="button" alt="Find Out More Button" style="display: inline-block;">Find Out More</a>

        </div>

我所做的是:

  1. 设置link()显示为inline-block
  2. 移除了 H1 的上边距

这对我来说仍然感觉有点hack,但效果稍微好一些。您可能需要考虑为内容使用基于列的 flexbox (具有适当的间距),而没有元素级边距/填充。

关于html - Flexbox CSS 垂直对齐不完全居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901509/

相关文章:

php - 在php中的url中传递变量

css - &lt;style&gt; 在 <head> 之外在页面上呈现

css - 填充使用 z-index 改变整个布局

css -::selection 伪元素大纲属性

html - Flex 2 列,其中一列为固定宽度,另一列宽度为 100%

javascript - AngularJS:如何获取选定的选项值并将其发送到 Controller

javascript - 如何在 CSS 或 Javascript 中的所有页面上添加通知?

php - 使用 PHP 显示 Mysql 数据给我一个空白页面

html - flexbox 的边界框行为

html - 垂直和水平居中,同时遵守 flexbox 的 html 规则