Search code examples
htmlcssmargin

Why does font size change the size and padding of parent div?


I've encountered the following issue. Let's suppose i have something like that in .html file body:

html,
body {
  width: 99%;
  height: 99%;
  margin: 0px;
  overflow: hidden;
}

#container1 {
  display: flex;
  gap: 2%;
  width: 90%;
  height: 10%;
  border: 1px black solid;
}

.box {
  border: 1px black solid;
  background-color: yellow;
  width: 100%;
}

.box p {
  text-align: center;
}
<body>
  <div id="container1">
    <div class="box">
      <p>Text 1</p>
    </div>
    <div class="box">
      <p>Text 2</p>
    </div>

  </div>
</body>

Things i find strange are the following:

  1. The size of the yellow boxes stays the way it should until i change the font of 'p' tags inside of those.
  2. If i set the margin of 'p' tags to margin: 0; the text gets stuck to the top of yellow boxes. Why is it?

How do you increase the size of the font without changing the size of its parent container? And how do you make a custom 'p' tag perfectly centered inside of its parent div?


Solution

  • You set the height as a percentage. This will be a problem in smaller sizes. So set its height to px. Then give the same amount of height to the <p> as line-height. Also <p> has a margin by default. You need to zero it here. The following code has been modified.

        html,
        body {
          width: 99%;
          height: 99%;
          margin: 0px;
          overflow: hidden;
        }
    
        #container1 {
          display: flex;
          gap: 2%;
          width: 90%;
          height: 40px;
          border: 1px black solid;
        }
    
        .box {
          border: 1px black solid;
          background-color: yellow;
          width: 100%;
        }
    
        .box p {
          text-align: center;
          margin:0;
          line-height:40px
        }
        <body>
          <div id="container1">
            <div class="box">
              <p>Text 1</p>
            </div>
            <div class="box">
              <p>Text 2</p>
            </div>
    
          </div>
        </body>