user10747020
user10747020

Reputation:

How can I vertically stack different elements in CSS/HTML?

Newbie to CSS so bear with me. I am trying to vertically stack different items in HTML/CSS and can't get them to stack vertically with custom spacing. Here is what I have so far.

<p id="loginView">
        <input type="text" id="usernameField">
        <div></div>
        <input type="password" id="passwordField">
        <button id="loginButton">Login</button>
</p>


#loginView {
    text-align: center;
}

The output is all of the fields, username, password and button horizontally viewed. I am trying to get them stacked vertically and centered properly.

Here is what I currently have

Upvotes: 0

Views: 310

Answers (4)

Atul Rajput
Atul Rajput

Reputation: 4178

You should use the semantic HTML

.formWrapper {max-width: 400px; margin:0 auto;}
.text-center {
  text-align: center;
}

input {width: 100%;margin-bottom: 10px;}
<form class="formWrapper">
  <div class="form-group">
    <input type="text" id="usernameField">
  </div>
  <div class="form-group">
    <input type="password" id="passwordField">
  </div>
  <div class="form-group text-center">
    <button id="loginButton">Login</button>
  </div>
</form>

Upvotes: 0

Stefan Joseph
Stefan Joseph

Reputation: 555

Try using dispaly: flex; to get your items vertically aligned. Also I would advise you to use classes instead of id to reference your css styles. This is a sample code. Hope it helps you

HTML

<div class="d-flex flex-column align-items-start justify-content-center">
  <input class="m-2" type="text" id="usernameField" />
  <input class="m-2" type="password" id="passwordField" />
  <button class="m-2" id="loginButton">Login</button>
</div>

CSS

.d-flex {
  display: flex;
}

.flex-column {
  flex-direction: column;
}

.align-items-start {
  align-items: flex-start;
}

.justify-content-center {
  justify-content: center;
}

.m-2 {
  margin: 0.5rem;
}

JS Fiddle Link: https://jsfiddle.net/SJ_KIllshot/dwkxo1va/

Upvotes: 1

kb_
kb_

Reputation: 187

You could also just put <br> tags in between each element within <p>:

    <p id="loginView">
        <input type="text" id="usernameField">
        <br>
        <input type="password" id="passwordField">
        <br>
        <button id="loginButton">Login</button>
   </p>

Upvotes: -1

DigitalJedi
DigitalJedi

Reputation: 1671

  1. You cannot put a <div>inside a p tag.
  2. You could just change all the children of #loginViewto display:block like so:

#loginView {
  text-align: center;
}

#loginView>* {
  display: block;
}
<div id="loginView">
  <input type="text" id="usernameField" />
  <div></div>
  <input type="password" id="passwordField" />
  <button id="loginButton">Login</button>
</div>

Additional: For centering stuff and aligning it in a profound way I would suggest using flexbox, its easy and can be used for a lot of different things:

https://yoksel.github.io/flex-cheatsheet/

Upvotes: 1

Related Questions