2016-10-06 26 views
0

我以前使用flexbox进行垂直对齐,但对于我在对齐时非常偏离中心的位置使用它的元素,特别是对于下面的JSFiddle示例中的div ,其中向包含文本其余部分的同一个div添加按钮会使对齐太低。Flexbox CSS垂直对齐不完全中心

代码:

#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/

+0

Flex对齐通过在容器中分配空闲空间来工作。如果你有一个单一的项目居中,这不是一个问题。但是,如果添加第二个项目,则会造成不平衡。现在你的对中关闭了,因为一边有更多的“重量”。您可以通过配重或使用绝对定位来平衡它。这些方法在此处详述:[在flexbox中的绝对定位](http://stackoverflow.com/q/36191516/3597276)。 –

+0

你有不同的高度,分别为100%,45%和80%。很难理解你想要达到的目标。你是否希望它在屏幕高度80%的div内垂直居中? – SomeGuy

回答

0

你必须有几个问题:

  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. 设置链接()显示,以inline-block的
  2. 删除上边距上H1

这仍然感觉有点的攻击我,但稍微好一点。您可能需要考虑对内容使用基于列的弹性框(具有适当的间距),而不使用元素级边距/填充。

+0

Thx你也可以投票 – Meir