【问题标题】:CSS Flex Stacking Items on Top of Each Other [duplicate]CSS Flex将项目堆叠在一起[重复]
【发布时间】:2017-11-21 02:39:47
【问题描述】:

我正在尝试将一些 <h1></h1> 文本和来自 Angular Material 的电子邮件表单放入具有彩色背景的 <div></div> 部分的中心。这些物品彼此叠放出来,就好像它们是层层叠叠的。电子邮件表单需要位于 <h1></h1> 标签下方。我可以让它正确对齐的唯一方法是使用position:flex,我怀疑这是根本原因。

这是我的 html 和 css:

<div class="top-section">

  <h1 class="top-h1">
    mytitle
  </h1>

  <md-input-container class="email-form" color="accent">
    <input mdInput placeholder="Email us" value="Your email address">
  </md-input-container>

</div>


.top-section {
  height: 350px;
  background-color: #04041b;
  align-items: center;
  display: flex;
  justify-content: center;
}

.top-h1 {
  color: #E8E8E8;
  font-size: 60px;
  position: absolute;
}

.email-form {
  color: white;
  font-size: 30px;
}

有什么想法吗?

【问题讨论】:

    标签: html css angular flexbox angular-material


    【解决方案1】:

    您在h1 上使用position: absolute 将其从页面流中移除,并将其相对于其最近定位的父级定位。所以其他元素不会围绕它流动。删除它。然后您的项目将并排显示,因为 flex 父级的默认 flex-directionrow。要垂直显示项目,请使用flex-direction: column,这些项目将在一列中相互堆叠,而不是在一行中并排显示。

    .top-section {
      height: 350px;
      background-color: #04041b;
      align-items: center;
      display: flex;
      justify-content: center;
      flex-direction: column;
    }
    
    .top-h1 {
      color: #E8E8E8;
      font-size: 60px;
    }
    
    .email-form {
      color: white;
      font-size: 30px;
    }
    <div class="top-section">
    
      <h1 class="top-h1">
        mytitle
      </h1>
    
      <md-input-container class="email-form" color="accent">
        <input mdInput placeholder="Email us" value="Your email address">
      </md-input-container>
    
    </div>

    【讨论】:

    • "并将其相对于其最近的父级定位" - 如果父级的位置不是默认值(静态),这将是正确的。在静态父绝对定位的情况下,h1 将相对于 body 元素对吗?
    【解决方案2】:

    我想这是因为您将.top-h1 设置为positionabsolute

    创建如下内容,它应该可以解决您的问题:

    <div class="container">
      <h1>Example</h1>
      <div class="form">
        <!-- ignore this div, this is an example of where your form will be. -->
      </div>
    </div>
    
    .container {
      height: 350px;
      background-color: #E0E0E0;
      width: 100%;
      margin: auto;
      text-align: center; 
    }
    
    .form {
      width: 100%;
      margin: auto;
    }
    

    这应该做你想做的事。如果我误解了这个问题,请回复,我可以调整我的回复,但这是我从你那里得到的,你希望元素不堆叠并且表单位于 h1 下方但保持居中。

    为了将来参考,如果你需要对齐一个 div,给它一个宽度,然后使用 margin: auto;

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-31
      • 2016-08-06
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多