html - 将 div 居中在 2 个 div 上的 CSS 指南
问题描述
我是 CSS 的初学者(无法正确定位 HTML 元素),我正在为 Angular 应用程序创建登录表单,我正在使用材料设计。
在我的应用程序中,我有以下代码,
<div class="firstDiv"></div>
<div class="secondDiv"></div>
<div class="loginDiv">
<mat-form-field>
<input matInput placeholder="Input">
</mat-form-field>
<br/>
<mat-form-field>
<input matInput placeholder="Textarea">
</mat-form-field>
</div>
注意:我将根据上述示例登录图像中的要求修改登录详细信息。
CSS文件如下,
.firstDiv {
height: 40%;
width: 100%;
top: 0;
left: 0;
right: 0;
position: absolute;
background-color: orangered;
display: inline-block;
}
.secondDiv {
position: absolute;
width: 100%;
bottom: 0;
height: 60%;
left: 0;
right: 0;
background-color:whitesmoke;
display: inline-block;
}
.loginDiv {
position: absolute;
transform: translate(-50%, -50%);
border: black;
background-color:white;
display: flex;
flex-direction: column;
}
我无法按要求获取表单,并且如果屏幕尺寸减小,则登录表单不适合屏幕尺寸,并且登录详细信息会变得混乱。
解决方案
这是一个解决方案:
body {
margin: 0;
padding: 0;
}
.container {
height: 100vh;
background: #ddd;
background-color: #23bdf5;
background: linear-gradient(to bottom, #34b9f7 0%, #34b9f7 40%, #f0f0f0 40%, #f0f0f0 100%);
position: relative;
text-align: center;
overflow: auto;
}
.center-content {
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 50px;
right: 50px;
}
.form-element {
height: 50vh;
background: white;
}
<div class="container">
<h1>Title</h1>
<div class="center-content">
<div class="form-element">
this is where your form would go
</div>
</div>
</div>
它通过执行以下操作来工作:
首先,我.container
为页面创建了一个元素,并为其添加了线性渐变背景;我使用了一个线性梯度生成器,你可以通过谷歌搜索找到一个。接下来,我将容器元素的高度设置为 100vh,即浏览器窗口高度的 100%;您可以在此处阅读有关视口单位的信息。
在容器中,我创建了一个.center-content
元素来将内容定位为在元素内垂直居中,.container
并且无论屏幕大小如何,始终距离容器边缘 50 像素,您可以将此值更改为适合您需要的任何值。
在此示例中,我将包含表单的元素设置为 50vh,只是向您展示了它的外观,但是您可以删除它并在元素内添加内容,然后添加填充以定义其尺寸。
推荐阅读
- sql - SQL Server:声明临时表存在,但不在 INFORMATION_SCHEMA 中
- sql - 如果 A 列的值对于 B 列的最大值为空,则获取 B 列的第二大值
- java - 保存大字节数组的 Java 堆内存
- mysql - 如何在 SQL 中创建条件计算列?
- firebase - 为什么我可以使用 onRequest 从 firebase 函数调用 firestore,但在使用 onCall 时却不能
- sql - 解释窗口函数框架
- r - 函数不适用于 dplyr 的选择包装器(包含,ends_with)
- javascript - 我怎么知道一个坐标(纬度和地段)是否在其他两个坐标的范围内?
- python - 在 selenium 中如何找出具有不同 id 的 XPATH 链接的确切数量?
- okd - 是否针对 4.x 代码库更新了 origin/CONTRIBUTING.adoc?