mystreie
mystreie

Reputation: 153

center the input text field

i have a question about how to put my input text box in the center of the page and be responsive.

Here is the HTML code:

<body>
        <div class="container container-padding50">
            <input type="text" class="js-userinput container-textinput" placeholder="mySearchApp">
    </div>
       <div class="message">
         <p>input anything you want search and press Enter</p>
         </div>
    <div class="js-container">      
         <!-- image shows here -->
    </div>

    <script src="javascript/main.js"></script>

</body>

and i have tried CSS with:

body {
    width: 80%;
    max-width: 1024px;
    margin: 0 auto;
}

.container-padding50 {
    padding-top: 50px;
    left:50%;
}

.container-textinput {
    text-aligen:center;
    width: 80%;
    /*display: relative;*/
    left: 50%;
    padding: 20px;
    font-size: 16px;
    font-family: Helvetica, sans-serif;
    border:none;
    border-bottom: 2px solid black;
}

I am intend to set my input field looks simple as only an underline with "mySearchApp", but I have tried with left:50% in order to make this in the middle of the page, could someone tell me why this does not work? Do I miss something here?

Upvotes: 0

Views: 2100

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371969

In order to use the left property, the element must be positioned.

The left CSS property participates in specifying the horizontal position of a positioned element. It has no effect on non-positioned elements.

https://developer.mozilla.org/en-US/docs/Web/CSS/left

Try this:

body {
  width: 80%;
  max-width: 1024px;
  margin: 0 auto;
}

.container-padding50 {
  position: relative;              /* NEW */
  padding-top: 50px;
  height: 80px;                    /* NEW */
}

.container-textinput {
  position: absolute;              /* NEW */
  left: 50%;
  transform: translateX(-50%);     /* NEW; see note below */
  text-align: center;
  width: 80%;
  padding: 20px;
  font-size: 16px;
  font-family: Helvetica, sans-serif;
  border: none;
  border-bottom: 2px solid black;
}
<div class="container container-padding50">
  <input type="text" class="js-userinput container-textinput" placeholder="mySearchApp">
</div>
<div class="message">
  <p>input anything you want search and press Enter</p>
</div>
<div class="js-container">
  <!-- image shows here -->
</div>

Why use transform when centering:

Upvotes: 3

Related Questions