代码之家  ›  专栏  ›  技术社区  ›  user3355736

CSS背景在居中文本上左对齐

  •  0
  • user3355736  · 技术社区  · 12 年前

    我有一个垂直菜单,其中每个项目都是 居中的 . 这是用ul/li完成的。

    我想要一个 可重复背景图像 对于每个项目,都在左侧对齐,但在右侧与内部文本宽度对齐。

    下面是我想做的一个例子: illustration as an image

    当然,可以将DIV添加到HTML结构中。

    谢谢

    2 回复  |  直到 12 年前
        1
  •  1
  •   user1741851 user1741851    12 年前

    这似乎不可能单独使用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

        2
  •  0
  •   Paulie_D    12 年前

    使用span和伪元素是可能的

    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 */
    }