如何将div固定在另一个上?

时间:2017-07-08 05:49:15

标签: css overflow css-position overlay centering

我正试图将overlaydiv)放在另一个上面。我设法将置于 overlay内。但是当滚动父级的内容时,它将被切断并且不会粘到中心。不幸的是,.parent { position: relative; height: 50px; width: 200px; border: 1px solid blue; white-space:nowrap; overflow: scroll; } .overlay { position: absolute; margin: auto; top: 0; left: 0; bottom: 0; right: 0; height: 100px; width: 100px; background-color: red; }不能只设置为固定:https://stackoverflow.com/a/20621323/1981832

到目前为止,这是我的代码:

https://codepen.io/anon/pen/PjyYwV



<div class="parent">
  <div class="overlay"></div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
&#13;
@register.inclusion_tag('blog/index_table.html', takes_context=True)
def DJ_LastDay(context):
    return {'posts': context['DJ_LastDay_posts'], 'request':context['request']}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

找到了获得我想要的方法。但是,我认为它不理想,因为它需要一个额外的<div class="main-template"> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> <div class="main-child"></div> </div> 元素。

wrapper
.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.wrapper {
  position: relative;
  display: inline-block;
  border: 1px solid red;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
  z-index: 100;
}

答案 1 :(得分:0)

您可以使用flexbox。此外,您还必须添加将占用内容宽度和高度的包装器并将文本移动到某个标签(即span):

.parent {
  height: 50px;
  max-width: 200px;
  border: 1px solid blue;
  white-space: nowrap;
  overflow: scroll;
}

.flex {
  position: relative;
  display: inline-flex; /* Width fit content */
  min-width: 100%; /* Not less than parent's width */
  min-height: 100%; /* Not less than parent's height */
  justify-content: center; /* Center items horizontally */
  align-items: center;  /* Center items vertically */
}

.overlay {
  position: absolute;
  height: 100px;
  width: 100px;
  background-color: red;
}
<div class="parent">
  <div class="flex">
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
      <div class="overlay"></div>  
  </div>
</div>