Home > Mobile >  Input field is not fitting well within a div
Input field is not fitting well within a div

Time:05-12

I can't understand why this input field with margin (at all sides) is not fitting well within that div. I was hoping to see the input with the right margin being shown.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="index.css">
  <title>CSS Tests</title>
</head>
<body>

  <div >
    <input type="Foobar">
  </div>
</body>
</html>
body {
  margin: 0;
}

.div2 {
  width: 100%;
  height: 100px;
  background-color:indianred;
}

.div2 input {
  width: 100%;
  margin: 10px;
  box-sizing: border-box;
}

input with 100% width and margin but not fitting well

CodePudding user response:

Width 100% will set the width to the available space, which in this case is the width of the parent div. Try setting the width to width: calc(100% - 20px); (subtract the margin out).

here is a fiddle link to demonstrate https://jsfiddle.net/2vcokm6x/

CodePudding user response:

The problem is that your width: 100% on the input element does not account for the margin being set. To work around this, you need to subtract 20px (for both the left and right margin) from the width. This can be achieved with calc(), as seen in the following:

body {
  margin: 0;
}

.div2 {
  width: 100%;
  height: 100px;
  background-color: indianred;
}

.div2 input {
  width: calc(100% - 20px);
  margin: 10px;
  box-sizing: border-box;
}
<body>
  <div >
    <input type="Foobar">
  </div>
</body>

  • Related