相应地将div的上边缘定位在另一个div的圆的中心点?

时间:2019-03-17 11:52:57

标签: javascript html css bootstrap-4

我有2个堆叠的div:div1包含一个圆形图像,div2包含一些文本。我希望div2向上移动并始终覆盖圆的一半,即div2的上边缘应位于圆的中心点。这是我的代码:

.coverLower {
background: #e1ecf4;
margin-top: -235px;
}
<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>

    <body>
      <div class="row">
        <div class="col-md-12">
          <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/03/Circle-withsegments.svg/1200px-Circle-withsegments.svg.png" style="width: 100%"></img>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 coverLower">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text 
        </div>
      </div>
    </body>
</html>

我手动将margin-top设置为一个值,以使其在全屏浏览器中都能正常工作,但是问题是如果我将屏幕调整为较窄的尺寸,则位置将不再正确。猜猜手动设置这是错误的,如何使位置始终响应正确?

1 个答案:

答案 0 :(得分:2)

您可以完全按照以下方式放置div:

.coverLower {
  background: #e1ecf4;
  position: absolute;
  top: 50%;
}
<html>

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <div class="row">
    <div class="col-md-12">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/03/Circle-withsegments.svg/1200px-Circle-withsegments.svg.png" style="width: 100%" />
      <div class="coverLower">
        text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        text text text text text text text text
      </div>
    </div>
  </div>
</body>

</html>