Search code examples
htmlcsscss-floatpadding

Why does a floating child element prevent the parent's padding from pushing elements inwards?


What I want vs. what I have:

h1 {
  color: blue;
  padding-left: .75em;
}

p {
  padding-left: 1.50em;
}

div {
  margin-bottom: 0.5em;
}

label {
  float: left;
  width: 16em;
  text-align: right;
}

input {
  margin-left: 1em;
}

.formDiv {
  text-align: center;
}

#border {
  border: .25em solid blue;
  display: inline-block;
}

#calculate,
#clear {
  margin-bottom: 1em;
}
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="salesTax.css">
    <title>Sales Tax Calculator</title>
  </head>

  <body>
    <main>
      <div id="border">
        <h1>Sales Tax Calculator</h1>
        <p>Enter Subtotal and Tax Rate and click "Calculate".</p>
        <form>
          <div class="formDiv">
            <label for="subtotal">Subtotal:</label>
            <input type="text" id="subtotal">
          </div>
          <div class="formDiv">
            <label for="taxRate">Tax Rate:</label>
            <input type="text" id="taxRate">
          </div>
          <div class="formDiv">
            <label for="salesTax">Sales Tax:</label>
            <input type="text" id="salesTax" disabled>
          </div>
          <div class="formDiv">
            <label for="total">Total:</label>
            <input type="text" id="total" disabled>
          </div>
          <div class="formDiv">
            <input type="button" id="calculate" value="Calculate">
            <input type="button" id="clear" value="Clear">
          </div>
        </form>
      </div>
      <script src="salesTax.js"></script>
    </main>
  </body>

</html>

As far as I can tell, the float: left applied to the labels here is causing them to fill up as much of #formDiv as possible to get the labels to the left of the inputs. Since I want the labels and inputs to be more centered, I thought I would apply padding to the #border, but all that does is expand it outward rather than pushing the inner elements inwards.

Why is that? Is there anything I can do to prevent that without removing any of the provided CSS? (The only CSS I can delete parts of is the CSS for #border. The rest is part of the specification, but can be added onto.)


Solution

  • Padding cannot "push in" the contents that are already at the minimum width. display: inline-block causes <div id="border"> to be no wider than its contents. Therefore, padding-right increases the width of <div id="border">.

    The only way to "push in" the inner elements would be to reduce the width of those elements.