2014-02-20 17 views
1

我想創建一個以div爲中心的標題,其左右兩個跨度。我設法這樣做了,但有兩個問題我似乎無法想到解決方案。使用跨度創建水平標題欄

  1. 首先涉及垂直居中的兩個邊界與 跨越中間跨度「標題」。
  2. 第二個是將左邊框全部展開到div的左邊緣,反之亦然右邊(顯然跨度的寬度需要從原始的寬度改變)。

使用兩個小時似乎是一個好主意,但它可能會涉及太多的黑客來做這麼簡單的事情。

HTML

<div id="container"> 
    <div class="title"> 
     <span class="border"></span> 
     <span>Title</span> 
     <span class="border"></span> 
    </div> 
</div> 

CSS

#container {background: #eee; height: 100px; width: 100%;} 
.title {margin: 0 auto; text-align: center; margin-top: 20px;} 
.title span:nth-child(2) {padding: 0 10px;} 
.border {display: inline-block; width: 40px; background: #000; height: 1px;} 

回答

1

我認爲你行之前和之後一個字想,不是爲什麼不使用僞元素?您將需要單個元素,不需要span,也不需要其他元素來實現該效果。

Demo

我已經作出了以下示例從頭,在這裏,正在使用:before:after僞創建虛擬元件,並且然後在用position: absolute;被設置爲top: 50;垂直定心相應定位它們,並那麼我會扣除每個僞元素的width,以便它不會與您的單詞重疊。

div { 
    margin: 150px; 
    position: relative; 
    float: left; 
} 

div:before, 
div:after { 
    content: ""; 
    width: 50px; 
    position: absolute; 
    top: 50%; 
    height: 1px; 
    background: #f00; 
} 

div:before { 
    left: -50px; 
} 

div:after { 
    right: -50px; 
} 

當你評論,如果你想將線從邊緣完全擴展到邊緣..不是包裹在span文本並進行更改,如下面的CSS

Demo 2(拓展100%)

<div><span>Hello</span></div> 

div { 
    text-align: center; 
    position: relative; 
} 

div span { 
    background: white; 
    position: relative; 
    z-index: 1; 
} 

div:before { 
    content: ""; 
    width: 100%; 
    position: absolute; 
    top: 50%; 
    left: 0; 
    height: 1px; 
    background: #f00; 
    z-index: 0; 
} 
+0

這幾乎正是我想它是,但唯一缺少的將是具有的寬度左邊框和右邊框展開到父div的邊緣。所以不是讓它們寬度爲50px,而是從左側和右側在標題本身和父div之間的空間的寬度。 –

+0

原來我的標題div居中,所以你的浮標不適用於我。 –

+1

@CarlEdwards http://jsfiddle.net/KXQjL/8/ –