😒今天写页面,有两个子元素因为 position 绝对定位重合在一起,用了z-index 分层做一个翻转div效果。
大致代码🌮🌮:
精简后的html:
<div class="flip-card">
<div id="login-box">
<input type="text" placeholder="手机号/邮箱" />
<input type="password" placeholder="密码" />
</div>
<div id="register-box">
<input type="text" placeholder="用户名" />
<input type="text" placeholder="手机号/邮箱" />
<input type="password" placeholder="密码" />
<input type="text" placeholder="验证码" />
</div>
</div>
精简后的css:
#login-box,
#register-box {
padding: 40px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
.flip-card {
width: 350px;
height: 500px;
position: relative;
border-radius: 13px;
overflow: hidden;
background-color: rgba($color: #000000, $alpha: 0.4);
}
很明显,login和register 会继承 父元素的高度 500px.这就造成loginbox下边还有一大片空白,而registerbox过多的input会超过500px
但是我两个子元素一个是 注册一个是登录,他们包含的input肯定不同。只要子元素高度自适应的,父元素不要高度固定即可解决。
第一步: 父元素不要高度固定
.flip-card {
width: 350px;
// height: 500px;
// position: relative;
border-radius: 13px;
overflow: hidden;
background-color: rgba($color: #000000, $alpha: 0.4);
}
第二步: 子元素高度自适应
![](https://img.haomeiwen.com/i15697111/1309f789b84f7da0.png)
显然,部分人可能也不清楚 relative 原来不会被移出正常文档流。
故而这里我尝试将 absolute 改为 relative
#register-box {
position: relative;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
没想到成功了.去搜索一堆资料还不如自己一试😆😆
这样一个 既可以基于定位,又能在父元素无固定高度时,子元素自适应高度就完成了。
![](https://img.haomeiwen.com/i15697111/3851ceabac287cb3.png)
![](https://img.haomeiwen.com/i15697111/c35220ee837d2c39.png)
网友评论