CSS Height/Width
CSS Height and Width: Responsive Sizing and Constraints
CSS dimension properties—width, height, min-width, max-width, min-height, and max-height—control how much horizontal and vertical space an element occupies. Relying on flexible constraints like max-width and min-height instead of rigid pixel sizes keeps layouts readable on every screen.
Fixed vs. Constrained Dimensions
Setting a fixed width: 800px forces mobile users to scroll sideways, and setting a fixed height: 200px cuts off translated or zoomed text. Instead, constrain widths with width: 100%; max-width: 800px; and allow containers to grow naturally with min-height.
pxandrem: Fixed pixels or root-font-relative sizes for icons, sidebars, and readable line lengths (max-width: 65ch).%: Relative to the parent container's dimensions.vwanddvh: Viewport-relative percentages (min-height: 100dvh;avoids mobile address-bar jump issues better than100vh).
.article-shell {
width: 100%;
max-width: 720px;
margin-inline: auto;
padding: 20px;
}
.hero-section {
min-height: 60dvh;
display: flex;
align-items: center;
}
.avatar {
width: 64px;
height: 64px;
aspect-ratio: 1 / 1;
}
Common Mistakes to Avoid
- Setting
heighton cards containing dynamic text: When longer headlines or mobile wraps occur, text spills right out of a fixed-height card. Usemin-heightinstead. - Using
width: 100vwon page sections: On Windows browsers with visible vertical scrollbars,100vwincludes the scrollbar width and causes annoying horizontal scroll. Preferwidth: 100%. - Setting
widthondisplay: inlinetags: Inline elements likespanignorewidthandheightuntil switched toinline-blockorblock.
Frequently Asked Questions
What does max-width do when combined with width: 100%?
width: 100%; max-width: 720px; lets a container stretch full-width on narrow phones while capping it cleanly at 720px on desktop monitors.
Why is min-height: 100vh sometimes taller than a phone screen?
Mobile browser URL bars shrink the visible area, making 100vh slightly too tall. Use min-height: 100dvh; (dynamic viewport height) for exact fit.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.