2017-06-19 88 views
3

我试图将一些<h1></h1>文本和Angular Material的电子邮件表单放入具有彩色背景的<div></div>部分的中心。这些物品堆叠在一起,就像是层层叠叠。电子邮件表单需要位于<h1></h1>标签下方。我可以正确对齐的唯一方法是position:flex,我怀疑这是潜在的原因。CSS 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; 
} 

有什么想法?

+0

这些问题可能试图解决同样的问题,但他们在措辞上的差异是惊人的。事实上,另一个问题并没有清楚地说明问题。它的标题写道:“防止从一侧到另一侧渲染柔性项目”。这并不能反映出我将Flex项目叠加在一起的问题。如果有人正在寻找这个问题的答案,另一个问题就不会出现,因为它措辞不当。我的问题很清楚。因此标题为:“Flex将堆叠项目放在彼此之上”。请重新考虑标记或关闭此问题。 –

回答

2

您在h1上使用position: absolute,该页面将其从页面流中移除,并将其相对于其最接近的定位父项进行定位。所以其他元素不会在其周围流动。删除。然后您的项目将并排显示,因为灵活父项的默认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>

1

我会想象这是由于这一事实,你有.top-h1position设置为absolute

创建类似下面的,它应该理清您的问题:

<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;

祝你好运。