Is it possible to set border width in percents or for example do something like this: 100px-1% in CSS ?

Dani AI

Generated

Short answer: you cannot give border-width a percentage value. The property accepts absolute length units (px, em, rem, vw, etc.) or the keywords thin|medium|thick — percent units are not valid (border-width — MDN).

If the goal is a border that scales, two practical paths work today. First, use calc() (supported broadly in modern browsers — check current support on caniuse) to combine length-like units (for example viewport units plus pixels) so the computed border is dynamic:

.element {
  border-style: solid;
  border-width: calc(0.4vw + 2px);
}

Note: putting a bare % inside a calc() for border-width won’t do what you expect because percentages only resolve where that property defines a percentage reference; border-width does not.

Second, if you want a border thickness that is a percentage of the element’s box, use a pseudo-element or a nested element to fake the border. Make the outer box the “border color” and inset an inner fill using percent offsets so the gap becomes the border:

.box {
  position: relative;
  background: #333; /* border color */
}
.box::before {
  content: "";
  position: absolute;
  top: 3%;
  right: 3%;
  bottom: 3%;
  left: 3%;
  background: #fff; /* inner content color */
  pointer-events: none;
}

This produces a visually proportional border that scales with the element size. As noted, calc() exists but check support for your target browsers; as suggested, nesting/pseudo-elements are a solid fallback and often cleaner than relying on percentage math for border-width.

Recommended Answers

All 2 Replies

css3 has calculated values
eg #mainContent { width: calc(100% - 20px) } newest browsers support some elements of css3
not sure which browsers support this part of css3
not sure if unsupported browsers degrade gracefully, or fall over and die,
so it may not be a useable (yet) feature

css2.1, more suppported, you can(may) style an element more readily by styling the containing element
may not help for a border specifically

browsers don't fully support css2.1yet
ie9 is due to support css3
Mozilla is due to release ff in 2011 with full css3
opera and ff have <selector>-o <selector>-moz support now for some css3

Just nest two box objects, each with one of those values. Put the % one on the outside. Make sure the padding on the outside one and the margin of the inside one are both set to 0.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.