首页 > 解决方案 > 将 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;
}

我无法按要求获取表单,并且如果屏幕尺寸减小,则登录表单不适合屏幕尺寸,并且登录详细信息会变得混乱。

标签: htmlcssangular-material

解决方案


这是一个解决方案:

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,只是向您展示了它的外观,但是您可以删除它并在元素内添加内容,然后添加填充以定义其尺寸。


推荐阅读