CSS Flex Stacking Items on top of each other

I am trying to place the text <h1></h1>

and form of an email from Angular Material, in the center of a section <div></div>

that has a colored background. Elements overlap each other as if they were layers. The email form should be under the tags <h1></h1>

. The only way I could properly reconcile this was with position:flex

, which I suspect is the root cause.

Here's my html and 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;
}

      

Any thoughts?

+3


source to share


2 answers


You use position: absolute

in h1

, which removes it from the page flow and positions it relative to its closest parent. This way, other elements won't flow around it. Delete this. Then your items will display side by side, as the default flex-direction

for the parent is flex row

. To display items vertically, use flex-direction: column

and items will stack on top of each other in a column instead of side by side in a row.



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

Run code


+2


source


I would guess it has something to do with what you have .top-h1

with position

set to absolute

.

Create something like the following and it should solve your problem:

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

      



This should do what you want. If I misunderstood the question, please answer me and I can adjust my answer, but this is what I get from you, wanting the elements not to stack and to keep the shape under h1 but stay centered.

For future reference, if you ever need to align a div, specify a width and then use margin: auto;

Good luck.

+1


source







All Articles