css - 具有绝对位置的子级具有完整的父级高度

标签 css flexbox

尝试重新创建此布局:

enter image description here

问题是黑色上面的白色框。我不知道黑匣子的高度。我怎样才能在其他人之上创建白框?

这是我的代码:

https://codepen.io/olefrankjensen/pen/oQyZpX?editors=1100

HTML

<div class="container">
  <div class="formbox">[login form markup here...]</div>
  <div class="box">
    <h1>Don't have an account</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus dicta cumque harum.</p>
    <button>SIGN UP</button>
  </div>
  <div class="box">
    <h1>Have an account</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus dicta cumque harum.</p>
    <button>LOGIN</button>
  </div>
</div>

CSS

// reset
h1, h2, h3, h4, h5, h6, p, button, div {
  margin: 0;
  padding: 0;
  line-height: 1;
}

// font
@import url('https://fonts.googleapis.com/css?family=Roboto');

// colors
$white: rgba(255,255,255,.8);

:root {
  font-size: 16px;
}

body {
  background-image: url(
https://picsum.photos/1200/800?);
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Roboto', sans-serif;
  color: $white;
}

.container {
  width: 900px;
  margin: 50px auto;
  background: rgba(0,0,0,.5);
  position: relative;
  display: flex;
}
.box {
  padding: 5rem 3rem;
  float: left;

  h1, p {
    margin-bottom: 1rem;
  }

  button {
    padding: 1rem 2rem;
    background: transparent;
    border: 2px solid $white;
    border-radius: 6px;
    color: $white;
    text-align: center;
    font-size: 1rem;   
    cursor: pointer;
    text-transform: uppercase;
  }
}

.formbox {
  width: 500px;
  background: white;
  margin-left: -50px;
  margin-top: -25px;
  box-shadow: 0 0 50px black;
  display: block;
  position: absolute;
}

我必须对 .formbox 进行绝对定位,以免它“干扰” flex 容器 .container 中的其他 flex 元素。但结果它没有高度。

我怎样才能让登录叠加层达到其父级的全高?

最佳答案

当位置是绝对位置时,topbottomrightleft 属性相对于第一个父级起作用使用 position: relative

所以,你并不真的需要 margin-top: -25pxmargin-left: -50px,你可以只添加 top: - 25px;底部:-25px; left: -25px.formbox 就完成了。如果您需要将其向右移动,只需添加 right: XXpx 并删除 left(或设置一个正值,如 left: 50% ).

https://codepen.io/anon/pen/gQKWNq?editors=1100

关于css - 具有绝对位置的子级具有完整的父级高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472262/

相关文章:

html - 给同级元素 "padding"作为 flexbox 属性 justify-content : space-around

CSS 浏览器不一致 : Margins on abs element inside a centered flexbox

css - Flex - 三列,3d 超出屏幕

html - 如何在 CSS 中将元素居中(垂直)对齐?

css - 如何使用 Node 模块中的 Font Awesome 图标

css - 制作 :focus work in ie7 using css?

CSS 多列蛇形图案

css - 在 Flexbox 中将边距设置为 auto

html - 位置 :fixed issue in IO S safari

css - 作为一行的 Bootstrap 列表组元素超出了面板边框