双 Div 仅使用 FlexBox 居中和重叠

Double Div Centering And Overlapping Using FlexBox Only

使用 flexbox 方法,我想 "double center" 两个单独的 divs: svgtext 这样它们 彼此重叠 ,同时在垂直和水平方向上都恰好在彼此的中心轴点上居中,无论它们多高或多宽。

初始状态是 svg div 所示。鼠标悬停时,svg 隐藏,text 显示:

jsFiddle demo

在这里,第一个 svg div 使用 flexbox 的神奇 margin: auto

很好地居中

然而,第二个 text div 使用繁琐的手动定位 hack,高度是猜测的,当字体大小改变等时不起作用

如何仅使用 flexbox 使 text 优雅地居中,重叠 svg

对于跨浏览器支持,您需要使用 transform: translate,因为浏览器处理绝对元素的方式不同

text{
    position: absolute;
    left: 0;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
    text-align: center;
}

堆栈片段

container{
    display:flex;
    background: #DDD;
    position: absolute;
    color: rgba(0,0,0,0);
    width: 300px;
    height: 300px;
}

svg {
    margin: auto; /* CENTERSsvg graphic in the middle of container WORKS ELEGANTLY */
    width: 100px;
    height: 100px;
    opacity:1;
    fill: red;
    transition: all 500ms ease;
}

text{
    position: absolute;
    left: 0;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
    text-align: center;
}

container:hover svg {
    opacity: 0;
}

container:hover text {
    color: black;
    opacity: 1;
    transition: all 500ms ease;
}
<a href="#">
    <container>
          <svg viewBox="0 0 200 200"><rect width="200" height="200" /></svg>
          <text>Here Goes My Centered Text</text>         
    </container>
</a>


根据评论更新

要使用 Flexbox 的居中功能,可以创建 2 个容器,层叠放置,就像我们在 Flexbox 可用之前一直采用的方式。

此解决方案不需要 translate,它使用 Flexbox 使项目在水平和垂直方向居中,而不管它们各自的大小。

container {
    display:flex;    
    align-items: center;
    justify-content: center;
    background: #DDD;
    color: rgba(0,0,0,0);
    position: absolute;
    left: 0; top: 0;
    width: 300px;
    height: 300px;
}
container + container{
    background: transparent;
    pointer-events: none;
}
svg {
    width: 100px;
    height: 100px;
    opacity:1;
    fill: red;
    transition: all 500ms ease;
}
text{
    width: 100%;
    text-align: center;
}
container:hover svg {
    opacity: 0;
}
container:hover + container text {
    color: black;
    opacity: 1;
    transition: all 500ms ease;
}
<a href="#">
  <container>
    <svg viewBox="0 0 200 200">
      <rect width="200" height="200" />
    </svg>
  </container>
  <container>
    <text>Here Goes My Centered Text</text>
  </container>
</a>