Home > other >  Is there a better way to achieve this layout?
Is there a better way to achieve this layout?

Time:09-22

I've been scratching my head trying to achieve what seemed like a pretty simple layout at first but I'm still nowhere close. Basically a horizontally centered header and a form underneath. The part I'm having trouble with is vertically aligning the inputs with the header.

enter image description here

Below is an image of my solution and the code

my solution

<div class="main">
    <h3>Customer Portal Login</h3>
    <label for="cid">Customer ID</label>
    <label for="password">Password</label>
    <form id="loginForm"></form>
    <input form="loginForm" id="cid" name="cid" type="text" required>
    <input form="loginForm" id="password" name="password" type="password" required>
    <input type="submit" value="LOG IN">
</div>
.main {
    display: grid;
    grid-gap: 1.5rem;
    align-items: center;
    border-top: 9px solid #0993B8;
    grid-template-columns: repeat(3, 1fr);
    grid-template-areas:
        "title title title"
        "labelCid inputCid ."
        "labelPasswd inputPasswd ."
        ". inputSubmit ."
}

.main h3 {
    text-align: center;
    grid-area: title;
}

label[for="cid"] {
    justify-self: end;
    grid-area: labelCid;
}

label[for="password"] {
    justify-self: end;
    grid-area: labelPasswd;
}

input[id="cid"] {
    grid-area: inputCid;
}

input[id="password"] {
    grid-area: inputPasswd;
}

input[type="submit"] {
    justify-self: center;
    grid-area: inputSubmit;
}

The problem with this is that I included the header in the grid and I can't style the form separately to add padding and a background-color. Is there a better way to do this?

CodePudding user response:

Why not put all of the required elements in the form and apply display:grid to that for layout?

.main {
  width: 90%;
  margin: auto;
}

form {
  display: grid;
  background: grey;
  grid-gap: 1.5rem;
  padding-bottom: 1.5rem;
  ;
  align-items: center;
  border-top: 9px solid #0993B8;
  grid-template-columns: repeat(3, 1fr);
  grid-template-areas: "title title title" "labelCid inputCid ." "labelPasswd inputPasswd ." ". inputSubmit ."
}

.main h3 {
  text-align: center;
  grid-area: title;
}

label[for="cid"] {
  justify-self: end;
  grid-area: labelCid;
}

label[for="password"] {
  justify-self: end;
  grid-area: labelPasswd;
}

input[id="cid"] {
  grid-area: inputCid;
}

input[id="password"] {
  grid-area: inputPasswd;
}

input[type="submit"] {
  justify-self: center;
  grid-area: inputSubmit;
}
<div class="main">
  <h3>Customer Portal Login</h3>
  <form id="loginForm">
    <label for="cid">Customer ID</label>
    <label for="password">Password</label>

    <input form="loginForm" id="cid" name="cid" type="text" required>
    <input form="loginForm" id="password" name="password" type="password" required>
    <input type="submit" value="LOG IN">
  </form>
</div>

  • Related