Pixel Border and Percentage width in Proportion

岁酱吖の 提交于 2019-12-03 07:08:08

Unfortunately, yes, you're out of luck. One hacky way to get around this problem is with a wrapper div that you use to create your border. So the outside div would be 57% (in your example) with a background that is the color of your desired border. Then, the inner div would have a width of 96% or so (play with the exact number to find a border that is appropriate for your design).

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')
}

You could use an inset box-shadow instead of a border:

box-shadow: 0px 0px 0px 10px red inset;

Just pad the inside of the container to compensate.

Edit: I write "pad" but of course if you use padding it'll throw off the box dimensions. Margin the content inside instead.

The accepted answer is not correct. You actually have 2 options:

Use the box-sizing property, so all the paddings and borders are considered part of the size:

.column {
    width: 16%;
    float: left;
    margin: 0 2% 0 2%;
    background: #03a8d2;
    border: 2px solid black;
    padding: 15px;
    font-size: 13px;

    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

Or, use the outline property instead of the border property. You will still have problems with the paddings, but it's easier to add. Example:

.column {
    width: 16%;
    float: left;
    margin: 0 2% 0 2%;
    background: #03a8d2;

    outline: 2px solid black;
}

Full explanation: http://designshack.net/articles/css/beating-borders-the-bane-of-responsive-layout/

RobW

If you want to stay semantic you can use div { box-sizing:border-box; } or some absolutely positioned :after elements. See the post How do I add 1px border to a div whose width is a percentage?

This link gives nice explanation on two solutions for this problem:

http://designshack.net/articles/css/beating-borders-the-bane-of-responsive-layout/

In CSS3 you can also use the new box-sizing property to include the pixel and padding count into the width of the element:

box-sizing: border-box;

If possible, depending on your design, what I like to do is put the border as an absolute div with a width of 3px ( for example ) and a height higher than its parent div. I then set overflow hidden on the parent div.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!