How to make an element width: 100% minus padding?



Let’s say we have padding: 50px 10px; for the input and want it to be 100% of the parent div's width. Using width: 100%; is not working. To fix it, we can place the input in a div with position: relative and a fixed height. This will form the element width to be 100% minus padding.

We have set the position to be relative with fixed height −

.container { position: relative; height: 30px; }

The position of the input is set absolute −

content { position: absolute; left: 0; right: 0; padding: 3px 10px; }

Example

Let us see the complete example −

<!DOCTYPE html> <html> <head> <style> .demo { border: thin solid orange; } .container { position: relative; height: 30px; } .content { position: absolute; left: 0; right: 0; padding: 3px 10px; } </style> </head> <body> <h1>Fix</h1> <div class="demo"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. <div class="container"> <input class="content" type="text" /> </div> Nunc auctor efficitur sapien, luctus faucibus mi dictum nec. </div> </body> </html>

Output


Advertisements