How to useFlexbox Container Method in CSS
Here, we are achieving the “width: 100% – padding” for an element by involving the flex container (‘display: flex’) with the centered content alignment of (‘justify-content: center’). This assures that the element’s width is the full width of its parent while taking the specified padding.
Example: In this example, we are using Flexbox Container Method to make an element width: 100% minus padding.
HTML
<!--Example 2--> <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < link rel = "stylesheet" href = "styles.css" > < title >Element Width Examples</ title > </ head > < body > < div class = "container" > < h1 class = "geeks-title" > w3wiki </ h1 > < div class = "example" > < h2 >Without 100% Minus Padding</ h2 > < p > This < code >< div ></ code > element has its width set to 100%, including padding. </ p > < div class = "box-with-padding" > Content without 100% minus padding </ div > </ div > < div class = "example" > < h2 >With 100% Minus Padding</ h2 > < p > This < code >< div ></ code > element uses a flex container to achieve < code >width: 100% - padding</ code >. </ p > < div class = "box-minus-padding-container" > < div class = "box-minus-padding" > Content with padding </ div > </ div > </ div > </ div > </ body > </ html > |
CSS
/* style.css*/ body { font-family : Arial , sans-serif ; background-color : #f0f0f0 ; margin : 0 ; padding : 0 ; } .container { max-width : 800px ; margin : 0 auto ; padding : 20px ; } .geeks-title { color : green ; text-align : center ; } .example { margin : 20px 0 ; padding : 20px ; background-color : #fff ; border : 1px solid #ccc ; box-shadow: 0 2px 4px rgba( 0 , 0 , 0 , 0.1 ); } .box-with-padding, .box-minus-padding { padding : 10px ; margin-bottom : 10px ; color : white ; text-align : center ; } .box-with-padding { background-color : #007bff ; /* Blue color for the box with padding */ } .box-minus-padding-container { width : 100% ; padding : 10px ; /* Padding for the container */ box-sizing: border-box; background-color : #ffffff ; /* Light blue background color */ } .box-minus-padding { background-color : #dc3545 ; /* Red color for the box with minus padding */ } .box-minus-padding-container { display : flex; justify- content : center ; } |
Output:
How to make an element width: 100% minus padding ?
In this article, we will see different examples to make an element’s width: of 100% minus padding. We have a few methods to make an element width: 100% minus padding which are described in detail below.
Table of Content
- Using ‘calc()’ and ‘box-sizing’
- Using Flexbox Container Method