如何将Divs移至绝对Div的底部和顶部

  • 本文关键字:Div 底部 顶部 Divs html css
  • 更新时间 :
  • 英文 :


我有一个codepen链接,我有一个绝对定位的div,有两个孩子。

我试图将一个孩子移至DIV的顶部,而另一个孩子则将其转移到底部,但用bottom:0top:0弄清楚了。我还尝试仅将内容的宽度用于其中一个元素,而不是父元素的整个宽度。

更改CSS:

.event-type-label{
  background: rgba(161,178,166,.8);
  border-radius: 2px;
  overflow: hidden;
  font-family: Lato;
  letter-spacing: 1px;
  text-transform: uppercase;
  color: #fff;
  position: absolute;
  top: 0;
  font-size: 0.8em;
  font-weight: 300;
  letter-spacing: .05em;
  line-height: 1;
  padding: 5px;
}
.event-header-title {
color: #fff;
position: absolute;
bottom:0;
font-family: Lato;
font-size: 3em;
font-weight: 300;
line-height: 120%;
margin: .5rem 0;
}

向孩子们添加position:absolute将解决您的问题。由于绝对定位元素仅具有内容的宽度。

进行了几次CSS调整 - 您很接近!只需与topbottom一起使用position: absolute,而position: relative则需要正确的元素。

这样做,该元素的宽度自动限于其内容。

查看我的评论以查看添加和删除的内容。

html,
body {
  height: 100%;
  width: 100%;
  box-style: border-box;
  margin: 0px
}
.event-page {
  width: 100%;
  height: 100%
}
.event-page-header {
  position: relative;
  height: 450px;
  max-height: 70vh;
  padding: 0 0 1.75rem;
  width: 100%;
}
.event-page-header .event-header-content {
  width: 100%;
  height: 100%;
  /*position: absolute; // removed */
  z-index: 200;
  padding: 0 20px;
  /*bottom: 0; // removed */
  /* added 1 line: */
  position: relative;
}
.event-type-label {
  background: rgba(161, 178, 166, .8);
  border-radius: 2px;
  overflow: hidden;
  font-family: Lato;
  letter-spacing: 1px;
  text-transform: uppercase;
  color: #fff;
  font-size: 0.8em;
  font-weight: 300;
  letter-spacing: .05em;
  line-height: 1;
  padding: 5px;
  /* added 2 lines: */
  position: absolute;
  top: 0;
}
.event-header-title {
  color: #fff;
  font-family: Lato;
  font-size: 3em;
  font-weight: 300;
  line-height: 120%;
  margin: .5rem 0;
  /* added 2 lines: */
  position: absolute;
  bottom: 0;
}
.event-header-image {
  background: red;
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 100;
}
@media (min-width: 769px) {
  .event-header-image::after {
    background: linear-gradient(rgba(65, 77, 87, 0), rgba(65, 77, 87, .7));
    bottom: 0;
    content: '';
    height: 70%;
    left: 0;
    position: absolute;
    width: 100%;
  }
}
<div class='event-page'>
  <header class='event-page-header'>
    <div class="event-header-content">
      <div class="event-type-label">Event Tag</div>
      <h1 class="event-header-title">Event Title</h1>
    </div>
    <div class='event-header-image'></div>
    <div class="clear"></div>
  </header>
</div>

您可以使用 flex -box,例如此示例。或者只使用position: absolute并将所有样式添加到子span中以使用所需的空间。

最新更新