CSS: Width in percentage and Borders

前端 未结 4 719
孤街浪徒
孤街浪徒 2020-11-22 02:26

I\'ve defined widths of the containers in percentage. I\'d like to add a border (3px on right side of a width), since container width is in % while the border width is in px

相关标签:
4条回答
  • 2020-11-22 02:59

    Just change px to vw like

    border-width: 10px;
    

    to

    border-width: 10vw;
    

    Its do whats percentage do....

    0 讨论(0)
  • 2020-11-22 03:00

    Use the box-sizing: border-box property. It modifies the behaviour of the box model to treat padding and border as part of the total width of the element (not margins, however). This means that the set width or height of the element includes dimensions set for the padding and border. In your case, that would mean the element's width and it's border's width would consume 30% of the available space.

    CSS box model

    Support for it isn't perfect, however vendor prefixes will catch most if not all modern browsers:

    .left {
        width: 30%;
        border: 3px solid #000;
    
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        -ms-box-sizing: border-box;
        box-sizing: border-box;
    }
    

    More information can be found on the MDN and Quirksmode.

    According to Quirksmode, using the 3 vendor prefixes above (-moz-, -webkit- and -ms-), you get support for all browsers, even IE8.

    0 讨论(0)
  • 2020-11-22 03:05

    The easiest cross-browser way is to NOT set the border on the outer divs, and instead set it on a NEW div inside .left. Simple, and works well.

    0 讨论(0)
  • 2020-11-22 03:12

    That's a bit tricky but check out this post on a way to get around it:

    • Percentage Plus Pixel Sizing (and Example)
    • Box Sizing on CSS-Tricks (and Example)

    The box-sizing property may also be of interest to you, check this out:

    • How do I add 1px border to a div whose width is a percentage?
    0 讨论(0)
提交回复
热议问题