2014-02-26 32 views
0

我有一个垂直菜单,其中每个项目是居中。 这是用ul/li完成的。居中文本左对齐的CSS背景

我想有一个可重复的背景图像为每个项目,这是全部对齐在左侧,但与右侧内部文本宽度对齐。

这里是我想要做的一个例证: illustration as an image

当然,有可能的DIV添加到HTML结构。

谢谢

+4

嗨和欢迎。请始终发布相关的CSS + HTML到您的问题 –

+1

这将是一件好事,如果您在小提琴中提供工作示例 – Harish

+0

我不确定这是否可能只使用CSS – pstenstrm

回答

1

这是可能的跨度和伪元素

Codepen Demo

HTML

<div class="wrapper"> /* not required */ 
    <ul> 
    <li class="center"><span>Some Long Text</span></li> 
    <li class="center"><span>Some Text</span></li> 
    <li class="center"><span>Text</span></li> 
    </ul> 
</div> 

CSS

ul { 
    padding: 0; 
    margin: 0; 
} 

/* THE GOOD STUFF */ 

li{ 
    overflow:hidden; /* hides all extra pixels */ 
    font-size:2em; 
    padding: 0; 
    margin-bottom:.5em; 
} 

.center { 
    text-align:center; 
} 

li > span { 
    diaplay:inline-block; 
    background:red; 
    position:relative; 
    padding-right:0.5em; 
} 

li.center > span:before { 
    content: ""; 
    position: absolute; 
    right:100%; 
    top: 0; 
    height:100%; 
    width:2000px; /* some really large number*/ 
    background:red; 
    margin-right:0; /* or remove and add padding-right to span */ 
} 
+0

那肯定是地狱是一个很棒的回答!我向你鞠躬! – nightgaunt

+0

想法基于:http://css-tricks.com/full-browser-width-bars/ –

+0

非常好!但在IE(8)中不起作用... – user3355736

1

这似乎不可能单独与CSS。所以我继续使用jQuery创建它。

HTML是

<ul> 
    <li><span class="center">Text</span></li> 
    <li><span class="center">Text big</span></li> 
    <li><span class="center">Text small</span></li> 
</ul> 

所有我的脚本做的是这样的。

$('li .center').each(function() { 
    var width = $(this).width(); 
    $(this).css({"paddingLeft": (200 - width)/2 + 'px'}); 
}); 

我已添加fiddle作为参考。

我希望你不会有麻烦添加背景图片,而不是#666 .center