Is there a way to give a div
element some padding INSIDE its border? For example, currently all the text inside my main div
element goes right to the edge of the element's border. I'd like, as a general rule on this site, to have at least 10 to 20 px of space between the text and the border.
Here's a screen shot to illustrate what I currently have:
Just use div { padding: 20px; } and substract 40px from your original div width.
Using CSS, you can center text in a div in multiple ways. The most common way is to use the text-align property to center text horizontally. Another way is to use the line-height and vertical-align properties. The last way exclusively applies to flex items and requires the justify-content and align-items properties.
The padding CSS shorthand property sets the padding area on all four sides of an element at once.
Padding is the space that's inside the element between the element and the border. Padding goes around all four sides of the content and you can target and change the padding for each side (just like a margin).
The CSS property you are looking for is padding. The problem with padding is that it adds to the width of the original element, so if you have a div with a width of 300px, and add 10px of padding to it, the width will now be 320px (10px on the left and 10px on the right).
To prevent this you can add box-sizing: border-box; to the div, this makes it maintain the designated width, even if you add padding. So your CSS would look like this:
div { box-sizing: border-box; padding: 10px; }
you can read more about box-sizing and it's overall browser support here:
https://www.paulirish.com/2012/box-sizing-border-box-ftw/
I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:
<div id="container"> <p id="text">Find Agents</p> </div>
All you need to do is apply this CSS:
#text { padding: 10px; }
Here is a fiddle showing the difference: https://jsfiddle.net/CHCVF/2/
Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:
.container * { padding: 5px 10px; }
Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: https://jsfiddle.net/CHCVF/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With