-1

I have an HTML input element. I want the element to be in the center, but because the right margin is not working, the element is slightly off to the right. box-sizing: border-box; does not resolve the issue.

My code

body {
  margin: 0;
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  margin: 40px;
  padding: 10px;
}

input {
  border-style: solid;
  border-color: #5f9341;
  border-width: 2px;
  width: 100%;
  box-sizing: border-box;
}
<html>

<head>
  <link rel="stylesheet" href="css/index.css">

  <script src="js/index.js"></script>
</head>

<body>
  <input type="text" id="input-el">
  <button id="input-btn">SAVE INPUT</button>
</body>

</html>
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
Amar Mesic
  • 69
  • 6

3 Answers3

1

You can wrap the input inside a div with a display of flex, and set that div's align-items to center to make it center horizontally, and set the flex-direction to column so that the button and input will be in the same column.

body {
  box-sizing: border-box;
  margin: 0;
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  margin: 40px;
  padding: 10px;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

input {
  border-style: solid;
  border-color: #5f9341;
  border-width: 2px;
  width: 100%;
  margin: 0;
}
<html>

<head>
  <link rel="stylesheet" href="css/index.css">

  <script src="js/index.js"></script>
</head>

<body>
  <div class="flex">
    <input type="text" id="input-el">
    <button id="input-btn">SAVE INPUT</button>
  </div>
</body>

</html>
jessica-98
  • 609
  • 1
  • 6
1

Since margins are added to percentage widths, the overall width of your input becomes 100% plus 80px (i.e. 40px each left and right margin).

If you need that margin, you can use the following value as width for the input element: width: calc(100% - 80px);, i.e. 100% wide, but minus the margin left and right:

body {
  margin: 0;
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  margin: 40px;
  padding: 10px;
}

input {
  border-style: solid;
  border-color: #5f9341;
  border-width: 2px;
  width: calc(100% - 80px);
  box-sizing: border-box;
}
<html>

<head>
  <link rel="stylesheet" href="css/index.css">

  <script src="js/index.js"></script>
</head>

<body>
  <input type="text" id="input-el">
  <button id="input-btn">SAVE INPUT</button>
</body>

</html>
Johannes
  • 64,305
  • 18
  • 73
  • 130
0

you make width:100% plus margin:40px which makes it impossible to center element.

You should take width:80% and make margin:auto; It will center element itself. Also it is important to know where should the save button be? Your goal needs to be clarified.