Search code examples
htmlcssdoctype

input box not centering


For some reason, my website isn't centering an input box. Code:

@import url("https://fonts.googleapis.com/css?family=Ubuntu");

body { background-color: black; }

#textInput {
    position: absolute;
    top: 50%;
    right: 50%;
    width: 300px;
}
<!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>Digturd.io</title>
</head>
<body>
    <input id="textInput" type="text">
</body>
</html>

The textbox I created is, for some reason, not centered into body. Is there any reason why? Codepen: https://codepen.io/ARandomUncreativeName123/pen/oNqqeoY


Solution

  • @import url("https://fonts.googleapis.com/css?family=Ubuntu");
    
    body { background-color: black; }
    
    #textInput {
        position: absolute;
        top: 50%;
        left: 50%;
      width: 300px;
      transform: translate(-50%,-50%)
    }
    <!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>Digturd.io</title>
    </head>
    <body>
        <input id="textInput" type="text">
    </body>
    </html>

    Just replace right: 50% to left: 50% and add transform.

    #textInput {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 300px;
        transform: translate(-50%,-50%)
    }