【问题标题】:How to stack text with pure CSS?如何用纯 CSS 堆叠文本?
【发布时间】:2012-11-30 19:52:14
【问题描述】:

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

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

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

有更好的选择吗?

【问题讨论】:

  • 你能张贴你想要的结果的图片吗.....
  • 参见dl.dropbox.com/u/16259019/Sample.png 示例:背景文本应较大,前景文本应垂直居中于背景文本之上。理想情况下,我很想用两个 div 元素和适当的 css 类来做到这一点。有什么想法吗?

标签: html css text alignment


【解决方案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 时,它们的相对对齐方式保持不变。

【讨论】:

    【解决方案2】:

    垂直对齐可以这样完成:

    .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;}
    

    如果verticalcentered 元素是你的文本,它们将在父元素中垂直居中并相互重叠,如果你正在寻找的话。

    【讨论】:

      【解决方案3】:

      我认为你看起来像这样:- 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;
      }
      

      【讨论】:

      • 示例已损坏
      【解决方案4】:

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

      当您输入新文本时,文本将被自动删除,然后默认文本将被删除

      //文本框

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

      //Javasript 代码

      //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'));
              } 
          });
      

      试试上面的选项。

      【讨论】:

      • 非常抱歉,但我的问题与input 元素无关:-/
      猜你喜欢
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多