Search code examples
htmlcssfocusmarginpadding

Changing the padding/margin of textinput on focus causes flow-out of parentdiv?


If I click in the input fields, the padding should go to zero so that the border is next to the text. Problem is that it keeps the width and thus flows out of the div parent ;[

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 400px;
    background-color: lightblue;
    border-radius: 5px;
    padding: 10px;
}
input[type=text] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0 8px 0;
    box-sizing: border-box;
    border: 2px solid grey;
    outline: none;
    display: block;
}
input[type=text]:focus {
    border: 2px dotted grey;
    padding: 0;
    margin: 21px;
}
</style>
</head>
<body>
<div>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname" value="John">
  <label for="lname">Last Name</label>
  <input type="text" id="lname" name="lname" value="Doe">
</form>
</div>
</body>
</html>

Solution

  • If you want to adjust for the changed padding, simply redefine the width in the :focus block as well, with something like

    width: calc(100% - 42px);
    

    So your :focus block should look something like:

    input[type=text]:focus {
        width: calc(100% - 42px);
        border: 2px dotted grey;
        padding: 0;
        margin: 21px;
    }
    

    The "42px" is because you defined the margin as 21px horizontal, so you need to account for there being 21px both left and right.