【问题标题】:How to align textarea's placeholder to the right bottom?如何将 textarea 的占位符对齐到右下角?
【发布时间】:2020-01-30 12:54:50
【问题描述】:

我可以首先将占位符定位在文本区域的右下角,但是在您输入一些文本并清除文本后,占位符的位置将被重置。有人知道如何防止占位符在清除文本后重置位置吗?

textarea {
    display: block; 
    height: 150px;
}

textarea::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  position:absolute;
  bottom: 10px;
  right: 16px;
  color: red;
}
<textarea placeholder="test">
</textarea>

【问题讨论】:

  • 为什么不使用label而不是占位符,因为占位符只是一个简短的提示,在用户输入值之前显示在输入字段中。

标签: css


【解决方案1】:

您可以使用::placeholder 选择器,然后只需应用text-align:right。然后让它出现在底部,应用transform:translateY(x),其中x是输入的高度。

textarea {
  width:500px;
  height:150px;
}

textarea::placeholder {
  text-align:right;
  transform: translateY(150px);
}
&lt;textarea placeholder="Lorem Ipsum"&gt;&lt;/textarea&gt;

【讨论】:

    【解决方案2】:

    如果您希望placeholder-texttextarea对齐,您可以简单地使用:

    textarea::placeholder {
      text-align: right;
    }
    

    为了在textarea底部 对齐placeholder-text,一种方法是给placeholder-text 一个line-height,它对应于:

    • 两倍于textareaheight 减去placeholder-textfont-size

    我们可以手动执行此操作(即,每次更新textareaheight 时,我们也会更新placeholder-textline-height)但这里使用CSS 自定义属性更有效calc()

    如果我们建立以下自定义属性:

    :root { 
      --textareaHeight : 150px;
      --placeholderFontSize : 14px;
    }
    

    那么我们知道placeholder-textline-height 总是:

    calc((var(--textareaHeight) * 2) - var(--placeholderFontSize))
    

    这意味着我们现在可以任意更改--textareaHeight--placeholderFontSize 的值,placeholder-textline-height 将始终正确计算。

    工作示例:

    :root { 
      --textareaHeight : 150px;
      --placeholderFontSize : 14px;
    }
    
    textarea {
        display: block; 
        height: var(--textareaHeight);
        padding: 0 6px 6px 0;
    }
    
    textarea::placeholder {
    text-align: right;
    font-size: --placeholderFontSize;
    line-height: calc((var(--textareaHeight) * 2) - var(--placeholderFontSize));
    color: red;
    }
    &lt;textarea placeholder="test"&gt;&lt;/textarea&gt;

    【讨论】:

    • 但是当我将文本区域框拖到更大的高度时,占位符无法相应地改变高度
    • 是的,你是对的。您是否需要将 textarea 框设为 resizable?如果没有,您可以在 CSS 中声明 textarea {resize: none;}
    【解决方案3】:

    你可以使用这个技巧

    * {
        box-sizing: border-box;
    }
    
    .form-group {
        position: relative;
        max-width: 200px;
    }
    
    label {
        position: absolute;
        right: 10px;
        bottom: 10px;
            display: inline-block;
    }
    
    textarea {
        width: 100%;
        padding: 20px;
    }
    <div class="form-group">
          <label>test</label>
          <textarea rows="5"></textarea>
        </div>

    这将始终坚持到文本区域的末尾,不管长度。还有一件事,你可以添加 jQuery 函数来隐藏标签,当它有一些价值时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 2016-09-24
      • 2011-10-07
      相关资源
      最近更新 更多