Pixel Border and Percentage width in Proportion

user1010892 picture user1010892 · Nov 16, 2011 · Viewed 26.5k times · Source

I think I might already know the answer to this one but I need a sanity check!

Say I have

#gridtest{
width:590px;
}

I could change the width to a percentage by using RESULT=TARGET/CONTEXT. In this case the context is a container with a max-width set to 1000px so I can do this:

#gridtestpercent{
width:59%; /*590/1000*/
}

If I were to shrink the window down the div would always be in the proportion to the its container. But what if I wanted to do

#gridtest{
width:570px;
border:10px solid red;
}

I can work the width out based on the target now being 570 but as the window is shrunk the proportions all go out of sync.

#gridtestpercentnoborder{
width:57%; /*570/1000*/
border:10px solid red;
}

I can't use percentage border. I don't want to use JS to keep checking the context and I can't use the CSS3 box-border declaration yet.

If I wanted to use the technique described in responsive web design by Ethan Marcotte where everything shrinks in relation to each other would I be out of luck if using a border?

Cheers!

Answer

Kariem Muhammed picture Kariem Muhammed · Apr 10, 2013

You could use CSS3 calc() function,

.selector{
  border: 5px solid black;
  width: -moz-calc(50% - 10px);
  width: -webkit-calc(50% - 10px);
  width: calc(50% - 10px);
}

SASS mixin

@mixin calc($property, $expression) {
  #{$property}: -moz-calc(#{$expression});
  #{$property}: -webkit-calc(#{$expression});
  #{$property}: calc(#{$expression});
}
article {
  border: 1px solid red;
  @include calc( width, '100% - 2px')
}