Share This!

Friday, October 2, 2015

CSS: making a div x% - n pixels wide

I ran into this in a website today.  I had a div that was 100% wide and I wanted it to be 100% - 15 pixels to align with another design element.  Originally I was trying to look for a way to do something like width:100px - 15px, but that is just not a CSS standard.  Then I thought of width:100%; margin-left:15px; margin-right:15px;. but that isnt right at all.

As it turns out, just nest two divs inside each other, and you have it made.


<div style="width:100%; border: 1px solid black; text-align:center;">
This is a 100% wide box
</div>

<div style="width:100%;">
    <div style="margin-left: 15px; margin-right: 15px; border: 1px solid black; text-align:center;">
    This is a 100% wide box with a 15px margin
    </div>
</div>


This is a 100% wide box
This is a 100% wide box with margins...
Look how it overflows to the right!
there is no way in CSS to calculate 100%-30px to get this right. And the margins and padding actually GROW the box!
This is a style="margin-left: 15px; margin-right: 15px;" div
inside a style="width: 100%;" div



...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *