Home > front end >  Self-taught: trying to center a textbox in the middle of the page by creating a div and using flex.
Self-taught: trying to center a textbox in the middle of the page by creating a div and using flex.

Time:03-10

.align {
  background: white;
  display: flex;
  align-items: center;
  margin: 0 auto;
  width: 60%;
}
<div >
  <p> This is filler text for a pretend blog </p>
</div>

Do I just add a bunch of padding to the top of the body? It does the trick but feels clunky and doesn't explain why flex isn't working.

CodePudding user response:

The p element is at the vertical center of the .align element. This is not equal to being at the vertical center of the page. To make the p element be at the vertical center of the page, the .align element has to take up the whole height of the page. This could be done by applying height: 100vh to the .align element.

(If you want to horizontally center the p element, you have to apply justify-content: center to the .align element.)

(If the .align element is just for alignment, it could make sense to just remove it and simply apply

  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;

to the body:)

body {
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
<p>This is filler text for a pretend blog </p>

CodePudding user response:

CSS Grid makes the process pretty painless.

/* remove default margin provided by browser user agent */
html {
  margin: 0;
}

/* remove default top margin for exact vertical centering */
.align p {
  margin-top: 0;
}

.align {
  display: grid;
  place-items: center;
  min-height: 100vh;
}
<div >
  <p> This is filler text for a pretend blog </p>
</div>

CodePudding user response:

.align {
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60%;
  height: 50vh;
  border: solid green 1px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div >
  <p> This is filler text for a pretend blog </p>
</div>

CodePudding user response:

You need to set the height of the page and use justify-content: center; and align-items: center;

body {
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
}
<div >
  <p> This is filler text for a pretend blog </p>
</div>

  • Related