【问题标题】:CSS background left aligned on a centered textCSS 背景在居中的文本上左对齐
【发布时间】:2014-03-29 07:07:13
【问题描述】:

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

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

这是我想要做的说明: illustration as an image

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

谢谢

【问题讨论】:

  • 您好,欢迎您。请始终将相关的 CSS + HTML 发布到您的问题中
  • 如果您在小提琴中提供工作示例会很好
  • 我不确定这是否可以仅使用 CSS
  • 为此需要一点 JavaScript。不要认为仅靠 CSS 是可能的。

标签: css background centering


【解决方案1】:

可以使用 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 */
}

【讨论】:

  • 这肯定是一个很棒的答案!我向你鞠躬!!
  • 是的,但你没有提到这是一项要求。
  • 我没有责怪你 :),这只是给未来读者的便条。
【解决方案2】:

这似乎无法单独使用 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 以供参考。

希望您在为 .center 添加背景图片而不是 #666 时不会遇到问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2019-10-01
    • 2016-02-13
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多