CSS Borders: Distance from Object Edge?

前端 未结 2 1889
无人共我
无人共我 2021-01-04 09:02

Quick question. I was writing out some code and was curious if there is a way to add a border on a div that is 5px within the object - as in not on the actual edge of the di

2条回答
  •  我在风中等你
    2021-01-04 09:31

    I've never come across any property that resembles this, so I'd have to say, simply, 'no.'

    But then I'd feel bad for that, so all I could really suggest is wrapping the div you wish to 'sew on' within another div and styling the parent with the same background-color to emulate the look you're after. Here's some css for a possible take:

    .wrap {
        border-width: 0;
        background-color: #ffa;
        width: 50%;
        padding: 0.5em;
    }
    
    .wrap #panel {
        background-color: inherit;
        height: 6em;
        border: 5px dashed #f90;
        text-align: center;
    }
    

    And some html:

    This panel should look kinda sewn-on.

    And, finally, A JS Fiddle demo

    Okay, having just rediscovered this answer (thanks to the up-voter!), I can, now, provide an actual CSS-only no-extraneous-elements solution, using box-shadow:

    #panel {
        background-color: #ffa;
        height: 6em;
        border: 5px dashed #f90;
        text-align: center;
        width: 50%;
        margin: 30px auto 0 auto;
        box-shadow: 0 0 0 15px #ffa;
    }​
    

    JS Fiddle demo.

    The fourth parameter is the key, it defines the, uh, 'spread' of the shadow (the third parameter defines the 'fuzziness'/'diffusion' which in this case is 0), using the same background-color as the element itself gives the illusion that the border is within the element, while it's actually a shadow of the element extending out from the element.

提交回复
热议问题