CSS: fixed width height 2026-04-29
ai answer
css fixed width height
To give an element a fixed width and height in CSS, use the width and height properties with absolute units (usually px):
Basic Example
.fixed-box { width: 300px; /* fixed width */ height: 200px; /* fixed height */ /* Recommended additions */ box-sizing: border-box; /* makes padding/border part of the size */ overflow: auto; /* handles content that overflows */ }
Full HTML Demo
<!DOCTYPE html> <html lang="en"> <head> <style> .fixed-box { width: 300px; height: 200px; box-sizing: border-box; background: #4f46e5; color: white; padding: 20px; overflow: auto; /* scrolls if content is too big */ border: 3px solid #1e2937; } </style> </head> <body> <div class="fixed-box"> This box will always stay 300×200 pixels, no matter how much content you put inside. </div> </body> </html>
Making It "Always Fixed" (Extra Protection)
If you want to be extra sure the size never changes (e.g. inside flex/grid containers or with lots of content):
.fixed-box { width: 300px; height: 200px; min-width: 300px; /* prevent shrinking */ max-width: 300px; /* prevent growing */ min-height: 200px; max-height: 200px; box-sizing: border-box; overflow: hidden; /* or auto / scroll */ }
Common Use Cases & Tips
| Situation | Recommended CSS |
|---|---|
| Fixed card / widget | width: 320px; height: 400px; |
| Square element | width: 200px; height: 200px; |
| Responsive but fixed on mobile | width: 100%; max-width: 400px; height: 250px; |
| Inside Flexbox | flex: 0 0 300px; + height: 200px; |
| Inside CSS Grid | width: 300px; height: 200px; (grid usually respects it) |
Units You Can Use for Fixed Size
px— most common (recommended)pt,cm,in— physical units (rarely used for web)rem/em— still "fixed" relative to font size, but scales with user settings
Avoid %, vw, vh, fr if you want truly fixed dimensions.
Would you like the fixed size to maintain aspect ratio automatically, or do you need it for a specific layout (flex, grid, etc.)? I can give you a more targeted example.