如何使用纯CSS堆叠文本?

时间:2012-11-30 11:17:36

标签: html css text alignment

我想使用文本作为另一个文本的背景。基本上,通过使用具有适当divposition设置的两个z-index元素,这很容易,如Is there a way to use use text as the background with CSS?中所述。

我的问题是我想对齐两个文本,尽管它们的大小不同。背景文本较大,前景文本应与背景文本垂直对齐,以便两个文本的垂直中心位于同一位置。

我可以通过手动调整像素位置来实现这一点,但我必须为每个我想单独使用的字体大小执行此操作。而且,我永远无法确定这在每个浏览器中都能以相同的方式运行。

有更好的选择吗?

4 个答案:

答案 0 :(得分:1)

我用它来获得它:

<div style="position: relative; font-size: 100pt; height: 100px;">
  <div style="font-size: 2em; color: #f00; position: absolute; top: 0; left: -0.37em; bottom: 0; right: 0; z-index: -1; line-height: 0.4em;">
    B
  </div>
  Sample text
</div>

使用leftline-height属性,我可以对齐两个文本,当我增加容器的font-size时,它们的相对对齐保持不变。

答案 1 :(得分:0)

垂直对齐可以这样做:

.parent {
position:relative;
zoom:1;/*has layout for ie*/
}
.verticalcentered1, .verticalcentered2 {
position:absolute;
top:50%;
height:20px;
margin-top:-10px;/*half the height*/
}
.verticalcentered1 {z-index:1;}    
.verticalcentered2 {z-index:2;}

如果垂直中心元素是您的文本,它们将在父级中垂直居中并且彼此重叠,如果这就是您要查找的内容。

答案 2 :(得分:0)

我认为你看起来像这样: - DEMO

<强> HTML

<div id="container">
        <div id="background">Sample Some Text </div>
        B
</div>

<强> CSS

#container {
    position: relative;
    font-size:70px;
    color:#00c7ff;
    z-index:-1; 
}

#background {
    left: 20px;
    position: absolute;
    right: 0;
    top: 25%;
    z-index: 10;
    color:black;
    font-size:20px;
}

答案 3 :(得分:-1)

是的,您可以使用其他方式 - 占位符文本

键入新文本时将自动删除文本,然后删除默认文本

//文本框

<input  type="text" defaultvalue="Name" value="Name" name="add_name" id="add_name">

// Javasript Code

//For the placeholder
    $('#add-category input[type=text]').focus(function() {

        if ($(this).val() == $(this).attr('defaultValue')) {
          $(this).val('');
        }
      });

      $('#add-category input[type=text]').blur(function() {

        if ($(this).val() == '') {
          $(this).val($(this).attr('defaultValue'));
        } 
    });

尝试以上选项。