Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make element centered: margin-right not working

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading