2015-07-21 79 views
0

我有一個以text-align: center;爲中心的文本元素,我想在其右側放置另一個元素(小內嵌<span>)而不影響其位置。在中心元素的右側放置一個未知寬度的元素而不移動它

這兩個元素(尤其是span)都沒有已知大小,所以我無法在文本元素的左側使用偏移量邊距。有沒有辦法在純CSS中做到這一點?

強制性碼不起作用:

<div style="text-align: center;"> 
    <h3 id="centered-text">My centered text</h3> 
    <span class="to-the-right" style="background-color: blue;">BADGE</span> 
</div> 

回答

4

how's this?

#centered-text { 
 
    display: inline-block; 
 
} 
 
#to-the-right { 
 
    display: inline-block; 
 
    position: absolute; 
 
    margin-left: 4px; 
 
}
<div style="text-align: center;"> 
 
    <div id="centered-text">My centered text</div> 
 
    <div id="to-the-right" style="background-color: blue;">BADGE</div> 
 
</div>

我做你的H3不是H3,因爲它使徽章古怪出現高位上方的標題,但可能通過給予BADGE一個像「top:10px;」這樣的屬性可以很容易地得到糾正

+0

比我的簡單得多。豎起大拇指! – GolezTrol

+0

謝謝!並感謝修復我的代碼片段在StackOverflow中運行;我一直想弄清楚如何做到這一點,但從來沒有這樣做:P –

+1

與'普通'代碼按鈕相比,右側有兩個按鈕,並且您已經擁有一個簡單的jsFiddle-like編輯器。 – GolezTrol

1

如果你可以把h3span的包裝裏面,可以說居中包裝,以及跨度使用絕對定位包裝突出位置。

如果h3是整頁寬度(跨度將在可見區域之外),或者如果跨度包含較長的文本(可能會變得笨拙),這可能有點棘手。但是,這是一個開始,這些問題可能不是問題。

.wrapper { 
 
    display: inline-block; 
 
    position: relative; 
 
} 
 
h3 { 
 
    display: inline-block; 
 
    margin: 0; 
 
} 
 
.wrapper span { 
 
    display: block; 
 
    position: absolute; 
 
    left: 100%; 
 
    top: 0; 
 
}
<div style="text-align: center;"> 
 
    <div class="wrapper"> 
 
    <h3 id="centered-text">My centered text</h3> 
 
    <span class="to-the-right" style="background-color: blue;">BADGE</span> 
 
    </div> 
 
</div>

+0

儘管您的解決方案有效,但如果可能的話,我認爲最好避免使用包裝類。感謝貢獻:) – bardo

0

你的CSS是關閉的。給你的DIV ID,然後

#divid {margin-left:auto; margin-right:auto; width:100%;} 
h3 {text-align:center;} 
+0

http://jsfiddle.net/yfxcpo1d/ –

+0

這不是我試圖實現的效果。通過集中整個'#myspan',徽章本身有助於居中,所以文字向左。 – bardo

0

不使用定位的方法是使用display: flex和僞元素。我個人認爲oxguy3's way更好,但是如果你想遠離定位,那麼這也將成爲訣竅。

span { 
 
    background: blue; 
 
} 
 
    
 
div { 
 
    display: flex; 
 
    justify-content: center; 
 
} 
 
    
 
div:before, span { 
 
    content: ""; 
 
    flex: 1 1; 
 
} 
 
    
 
* { 
 
    margin: 0; 
 
    padding: 0; 
 
    box-sizing: border-box; 
 
}
<div> 
 
    <h3>My Centered Text</h3> 
 
    <span>BADGE</span> 
 
</div>

這確實有可能會或可能不會不要緊根據您的需求的幾個問題。如果div中需要其他元素,則需要進行一些重新配置,因爲任何新元素也會變爲flex-items並與h3居中混淆。

此外,您可能會注意到跨度現在擴展到div的邊緣。如果這不是一個問題,則加價幅度是罰款,是的,但如果它是那麼問題在其他元素包裝還修復了這個問題,像這樣:

span { 
 
    background: blue; 
 
} 
 

 
.container { 
 
    display: flex; 
 
    justify-content: center; 
 
    margin-bottom: 5%; 
 
} 
 

 
.container:before, 
 
.badge { 
 
    content: ""; 
 
    flex: 1 1; 
 
} 
 

 
* { 
 
    margin: 0; 
 
    padding: 0; 
 
}
<div class="container"> 
 
    <h3>My Centered Text</h3> 
 
    <div class="badge"><span>BADGE</span></div> 
 
</div>

這不是完美,如我所說,我更喜歡oxguy3's answer,但如果你想遠離定位,那麼我認爲這是一個很好的選擇。

這裏是codepen with both examples

+0

避免絕對定位的絕佳解決方案!我也喜歡flexboxes,但我更喜歡避免使用包裝元素,如果可能的話。 – bardo

相關問題