CSS Tip 1: Stop using position: absolute for centering.
Moving away from
position: absolute
for centering is a major milestone in writing modern, maintainable CSS. While the old method of combining top: 50% with transform: translate(-50%, -50%) worked, it often led to "blurry" text (due to sub-pixel rendering) and was difficult to manage in complex layouts.
Why Modern Centering Wins
Readability: align-items: center is self-explanatory; transform: translate(-50%, -50%) is a math trick.
Flow: Absolute positioning removes elements from the document flow, often causing parent containers to collapse to zero height. Flex and Grid keep the layout "aware" of the element's size.
Flexibility: Centering multiple items or changing alignment based on screen size is significantly easier with modern layout engines.
1. The Flexbox Method (Best for 1D Layouts)
Flexbox is the go-to for centering a single element or a row of elements. By applying styles to the parent, you control the child.
2. The Grid Method (The "One-Liner")
CSS Grid is the most concise way to center. If you have a single child element, place-items: center handles both the horizontal and vertical axes in one go.
HTML
<p>this is ok, but there is a shorter method. this one still uses:</p>
<pre>.align-center {
display:flex;
align-items:center;
justify-content:center;
}</pre>
<p>so its still fairly long, which is ok i guess.</p>
<div class="demo-box align-center">hi<br>..</div>
<pre>.parent {
display: grid;
place-items: center;
}</pre>
<p>this one is a bit better requiring only one additional line, but its still two after the display line</p>
<div class="demo-box parent">hi<br>..</div>CSS
.demo-box {
height:200px;
width:200px;
margin-bottom:10px;
text-align:center;
border-radius:10px;
background:teal;
color:white;
}
.align-center {
display:flex;
align-items:center;
justify-content:center;
}
/* almost a one liner, but its two */
.parent {
display: grid;
place-items: center;
}
this is ok, but there is a shorter method. this one still uses:
.align-center {
display:flex;
align-items:center;
justify-content:center;
}
so its still fairly long, which is ok i guess.
..
.parent {
display: grid;
place-items: center;
}
this one is a bit better requiring only one additional line, but its still two after the display line
..
