Is there a way to prevent anything overflowing out of an html element through automatically resizing children?

Issue

In the example below, is there a way to override the size of the h1 tags so they do not overflow (I do not want to just hide the overflow).

We really want the ‘strictContainer’ to be 100px of height and not bigger. I searched for an analoguous to size:auto but found nothing.

h1 {
  height: 80px; border:solid black
}

.strictContainer {
  height: 150px; border:solid gold
}
<div class="strictContainer">
  <h1>Hello
    </h1>
    <h1>Hello
    </h1>
</div>

Solution

Assuming you cannot modify the original CSS. You can override the size of h1 using a new rule make it have more precedence.
One way to fit both the h1 tags in the container is to make them have equal heights:

/* original rules */

h1 {
  height: 80px;
  border: 2px solid black
}

.strictContainer {
  height: 150px;
  border: 2px solid gold;
}


/* overrides */

.strictContainer>h1 {
  /* need to override default margins */
  margin: auto 0;
  /* make them have equal heights*/
  height: 50%;
  box-sizing: border-box;
  /* uncomment following to have auto height */
  /*height: auto;*/
}
<div class="strictContainer">
  <h1>Hello</h1>
  <h1>Hello</h1>
</div>

User agents(browsers) put default styles on some html elements. For example, Chrome has following style on h1 tags by default:

h1 {
  display: block;
  font-size: 2em;
  margin-block-start: 0.67em;
  margin-block-end: 0.67em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}

In order to fit both the tags we need to override margins. I used margin: auto 0;. This means vertical margin is auto and horizontal margin is 0.
We’ve used box-sizing: border-box; to make borders part of the dimensions. Otherwise we would have to calculate height using height: calc(50% - 4px);


solution 2 You can make the container a flexbox:

/* original rules */

h1 {
  height: 80px;
  border: 2px solid black
}

.strictContainer {
  height: 150px;
  border: 2px solid gold;
}


/* overrides */

.strictContainer {
  display: flex;
  flex-direction: column;
  justify-content: space-around; /* play with this */
}

.strictContainer>h1 {
  /* need to override default margins */
  margin: 0;
  height: auto;
  flex: 0 0 auto;
  /* for 50% height use this */
  /*flex: 1 0 auto;*/
}
<div class="strictContainer">
  <h1>Hello</h1>
  <h1>Hello</h1>
</div>

Note: In your code snippet you’ve used 150px height for the container so I’ve used the same. If your issue is with margins then you can use

Answered By – the Hutt

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.