2017-06-19 90 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;

祝你好運。