skip to Main Content

Why is the button not center???!!! I’m kind of new to CSS. I learned that align-items centers child elements on the cross axis. My button isn’t centering. Why isn’t this working?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>CSS Practice</title>
</head>
<body>
    <input type="button" class="button" value="Get Started"></input>
</body>
</html>
body {
    display: flex;
    align-items: center;
    justify-content: center;
}

.button {
    width: 200px;
    height: 100px;
    display: flex;
    justify-content: center;
}

I have no idea what is happening.

2

Answers


  1. The flex container’s children will be centered according to its height. By default, the height of the body element is just enough to contain its content, so align-items: center has no visible effect. Set the body’s height to be the height of the viewport to see the input being centered in the middle of the screen.

    body {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        margin: 0; /* prevent scrollbar */
    }
    
    Login or Signup to reply.
  2. You must set the height of the main parent so your CSS code would look like this:

    body {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh /* Height of the viewport (window) */
    }
    
    .button {
        width: 200px;
        height: 100px;
        display: flex;
        justify-content: center;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search