How to Make an Element Take Full Width in CSS
To make an element take full width in CSS, set its
width property to 100%. Ensure the element's parent container allows full width and consider using box-sizing: border-box; to include padding and borders within the width.Syntax
Use the width property to control the width of an element. Setting it to 100% makes the element span the full width of its parent container.
The box-sizing property controls how padding and borders affect the element's total width.
css
selector {
width: 100%;
box-sizing: border-box;
}Example
This example shows a div that takes the full width of its parent container, including padding and border.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Full Width Element Example</title> <style> .container { width: 300px; border: 2px solid #333; padding: 10px; } .full-width { width: 100%; box-sizing: border-box; background-color: #a0d8f1; padding: 10px; border: 1px solid #0077cc; display: block; } </style> </head> <body> <div class="container"> <div class="full-width">I take full width of my container including padding and border.</div> </div> </body> </html>
Output
A light blue box inside a 300px wide container, spanning the entire container width with visible padding and border.
Common Pitfalls
Setting width: 100% alone may cause the element to overflow if it has padding or border because the default box-sizing is content-box. This means padding and border add extra width beyond 100%.
Also, if the parent container has no set width or is smaller than expected, the element's full width will be limited by the parent.
css
/* Wrong way: causes overflow */ .element { width: 100%; padding: 10px; border: 2px solid black; box-sizing: content-box; /* default */ } /* Right way: includes padding and border inside width */ .element { width: 100%; padding: 10px; border: 2px solid black; box-sizing: border-box; }
Quick Reference
- width: 100%; makes element fill parent width.
- box-sizing: border-box; includes padding and border inside width.
- Ensure parent container has defined width or is block-level.
- Use
display: block;if element is inline by default.
Key Takeaways
Set width to 100% to make an element fill its parent's width.
Use box-sizing: border-box to include padding and border inside the width.
Make sure the parent container has a defined width or is block-level.
Inline elements need display: block to respect width settings.
Without box-sizing: border-box, padding and border can cause overflow.