2016-09-27 33 views
3

是否可以在每個角落開始的div的所有邊緣上都有部分邊框? 我想避免background-image property &使用CSS Only解決方案來實現此目的。從div的所有角落的部分邊框CSS

部分邊框可能使用僞:在屬性後,但我無法弄清楚如何在所有邊緣上使用它?

div應該看起來像一個焦點小部件,如附圖所示。

Desired result

感謝。

+0

你寫「部分邊框採用...是可能的」,你可以分享這個代碼,以及以何種方式(沒有)工作? –

+0

@FlorianHeer我嘗試TrevC提供的解決方案在這裏http://stackoverflow.com/questions/4131490/any-way-to-limit-border-length –

+1

@GaneshPutta「你的代碼」也被抄襲。至少可以得到信用..... – Stewartside

回答

0

當然,試試這個:

HTML:

<div></div> 

CSS:

div { 
    background: white; 
    padding: 1.7em; 
    position: relative; 
    width: 300px; 
    height: 300px; 
    margin: 3em auto; 
    border: solid 2px #d00; 
} 
div::before, div::after { 
    position: absolute; 
    background: inherit; 
    content: ''; 
    z-index: 1; 
} 
div::before { 
    width: 100px; 
    left: calc(50% - 50px); 
    height: calc(100% + 4px); 
    top: -2px; 
} 
div::after { 
    height: 100px; 
    left: -2px; 
    width: calc(100% + 4px); 
    top: calc(50% - 50px); 
} 
div > * { 
    position: relative; z-index: 2; /* ensure any child elements sit above pseudos */ 
} 

Fiddle

+0

If div '有內容初始化,內容將隱藏'僞元素' –

+0

不,它不會。閱讀最終的CSS定義。 – Utkanos

-1

您可以使用兩個額外的邊框元素來做到這一點,所以您不必屏蔽背景,並且可以擁有透明背景。

.element { 
 
    width: 200px; 
 
    height: 200px; 
 
    margin: 50px; 
 
    position: relative; 
 
    padding: 10px; 
 
} 
 
.top-border, 
 
.bottom-border { 
 
    position: absolute; 
 
    display: flex; 
 
    justify-content: space-between; 
 
    width: 100%; 
 
    height: 30%; 
 
    left: 0; 
 
} 
 
.top-border { 
 
    top: 0; 
 
} 
 
.bottom-border { 
 
    bottom: 0; 
 
} 
 
.top-border:after, 
 
.top-border:before, 
 
.bottom-border:after, 
 
.bottom-border:before { 
 
    content: ''; 
 
    width: 30%; 
 
    height: 100%; 
 
} 
 
.top-border:after, 
 
.top-border:before { 
 
    border-top: 1px solid green; 
 
} 
 
.bottom-border:after, 
 
.bottom-border:before { 
 
    border-bottom: 1px solid green; 
 
} 
 
.top-border:before, 
 
.bottom-border:before { 
 
    border-left: 1px solid green; 
 
} 
 
.top-border:after, 
 
.bottom-border:after { 
 
    border-right: 1px solid green; 
 
}
<div class="element"> 
 
    <div class="top-border"></div> 
 
    <div class="bottom-border"></div> 
 
    <div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis, libero!</div> 
 
</div>