The problem
<div class="card"> <h2>Lorem ipsum</h2> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea tempore cumque a, quis velit perferendis exercitationem asperiores incidunt reiciendis expedita iure laborum ipsa perspiciatis commodi esse eum dolorum quaerat dolores. </p> <p> Sint ipsam quia eligendi accusamus hic soluta! Dolores doloremque aspernatur cumque nesciunt distinctio quas esse, pariatur eius error eveniet deleniti ex voluptas nam. Reprehenderit ducimus libero veritatis non repellendus vero? </p> <p> Quod alias optio tenetur nesciunt dolores totam aliquam, accusamus at facere officiis eius eos, sed, quae aperiam. Quam consequatur dolores, adipisci mollitia id quaerat cum odio dolor porro, numquam officiis. </p> </div>
The heading and last paragraph have extra margin values we don’t need/want.
How we typically fix the problem
.card { h2, p { margin-block: 1rlh; } h2, p:last-child { margin-top: 0; } }
Note: The rlh
unit in CSS stands for “root line height.” It is a unit of measurement that is relative to the computed line height of the root element, typically the <html>
element. This unit allows for proportional spacing that adapts to the line height of the root element, ensuring consistent vertical rhythm in web design. Using rlh
, you can define height, spacing, or other dimensions relative to the root’s line height, making it easier to maintain a cohesive and scalable layout.
margin-trim
to the rescue
Adding the margin-trim
property to the parent container allows us to set the preferred margin on content elements and not worry about removing the top and bottom margins of the first and last items in the container.
.card { background-color: #fcf5e7; padding: 2rlh; margin-trim: block; h2, p { margin: 1rlh 0; } }
Leave a Reply