【问题标题】:How to center a div in another div using flexbox?如何使用 flexbox 将一个 div 居中在另一个 div 中?
【发布时间】:2018-05-15 22:31:58
【问题描述】:

我想制作一个底部为半圆形的标题图片。在这张图片的中间,我想要一个标题和一个按钮。我无法仅使用 flexbox 或引导程序将 div 与标题和按钮居中。 mx-auto (margin x auto) 有效,但 my-auto 无效,align-self-center 和 align-items-center 类无效,我必须添加 mx-auto。为了使圆形底部居中,我必须使用 margin-left: -25vw。将 div 居中的最佳方式是什么?

这是我的代码:

.image-wrapper {
 position: relative;
 width: 100vw;
 height: 100%;
 overflow: hidden;
}

.circular-bottom {
  width: 150vw;
  height: 90vh;
  margin-left: -25vw;
  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
  overflow: hidden;
}

.circular-bottom img {
  z-index: -1;
}

.title-box {
  position: absolute;
  top: 0;
  height: 100%;
  width: 100%;
}

.title-text {
  text-align: center;
  width: 40%;
 }
<div class="image-wrapper">
  <div class="circular-bottom d-flex justify-content-center">
    <img src="url/image" draggable="false">
   </div>
   <div class="title-box d-flex">
    <div class="title-text align-self-center">
      <h1>Title</h1>
      <a class="btn" href="#">button text</a>
    </div>
  </div>
</div>

图像包装防止水平滚动。圆形底部使用溢出隐藏使图像的底部变为圆形,圆形的形状更宽。这也是图片不是背景图片的原因,必须使用overflow hidden将其截断。

【问题讨论】:

    标签: html css flexbox bootstrap-4


    【解决方案1】:

    将justify-content: center 属性添加到弹性容器(在本例中为.title-box)应该可以工作,如下所示:

    .image-wrapper {
     position: relative;
     width: 100vw;
     height: 100%;
     overflow: hidden;
    }
    
    .circular-bottom {
      width: 150vw;
      height: 90vh;
      margin-left: -25vw;
      border-bottom-left-radius: 50%;
      border-bottom-right-radius: 50%;
      overflow: hidden;
    }
    
    .circular-bottom img {
      z-index: -1;
    }
    
    .title-box {
      justify-content: center;
      position: absolute;
      top: 0;
      height: 100%;
      width: 100%;
    }
    
    .title-text {
      text-align: center;
      width: 40%;
     }
    <div class="image-wrapper">
      <div class="circular-bottom d-flex justify-content-center">
        <img src="url/image" draggable="false">
       </div>
       <div class="title-box d-flex">
        <div class="title-text align-self-center">
          <h1>Title</h1>
          <a class="btn" href="#">button text</a>
        </div>
      </div>
    </div>

    我已经尝试过了,它对我有用。

    工作代码笔的链接:https://codepen.io/anon/pen/YLOwxX

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 2017-03-27
      • 2013-11-30
      • 1970-01-01
      相关资源
      最近更新 更多