To adjust the size of h1
without modifying the original CSS, you can create a new rule with higher precedence. To ensure both h1 tags fit in the container, you can give them 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;
}
To accommodate both tags, we must override margins. I used margin: auto 0;
where vertical margin is set to auto and horizontal margin is 0.
We've included box-sizing: border-box;
to encompass borders in the dimensions. Otherwise, height calculation would require height: calc(50% - 4px);
Solution 2: Transforming the container into 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: Your code snippet specifies a 150px height for the container, so I've maintained that. If the issue lies with margins, consider adjusting them.