代码之家  ›  专栏  ›  技术社区  ›  Sagar Kharche

如何在溢出时将元素左右两侧的文本水平等分?

  •  0
  • Sagar Kharche  · 技术社区  · 8 年前

    当用户在DIV中键入文本(contenteditable=“true”)时,我试图对DIV内容实现以下效果。

    .editor{
    宽度:200px;
    高度:200px;
    轮廓:0;
    位置:绝对;
    左:25%;
    边框:1倍纯绿色;
    }

    .editor {
      width: 200px;
      height: 200px;
      outline: 0;
      position: absolute;
      left:25%;
      border: 1px solid green;
    }
    <div class="editor" contentEditable="true"><p>type here ...<p></div>
    4 回复  |  直到 8 年前
        1
  •  3
  •   SuperDJ Franklin Rivero    8 年前

    .editor {
        width: 200px;
        height: 200px;
        outline: 0;
        position: absolute;
        left:25%;
        border: 1px solid green;
        word-wrap: normal;
    }
    .editor p {
       position: absolute;
       left: 50%;
        transform: translateX(-50%);
    }
    <div class="editor" contentEditable="true"><p>type here ...<p></div>
        2
  •  0
  •   SuperDJ Franklin Rivero    8 年前

    var contents = document.getElementsByClassName('content');
    
    for(let i = 0; i < contents.length; i++)
    {
      var content = contents[i];
      var editor = content.parentElement;
      var width = content.getBoundingClientRect().width;
      content.style.setProperty('--content-width', width+'px');
      
      
      editor.addEventListener('input', function() {
      var width = content.getBoundingClientRect().width;
      content.style.setProperty('--content-width', width+'px');
      });
    }
    .editor {
      width: 200px;
      height: 200px;
      outline: 0;
      position: relative;
      left:25%;
      border: 1px solid green;
    }
    
    .editor p {
      white-space: nowrap;
      position: absolute;
      z-index: 1;
      width: auto;
      min-width: var(--content-width);
      top: 50%;
      left: calc(-1 * (var(--content-width) / 4));
    }
    <div class="editor" contentEditable="true"><p class="content">type here ...<p></div>
        3
  •  0
  •   Bhanu0202    8 年前
    p {
      position: relative;
      right: 100px;
      width: 400px;
      text-align: center;
    }
    

        4
  •  0
  •   enbermudas    8 年前

    .input-outline {
          width: 100px;
          margin: 25px auto;
          border: 1px solid green;
          position: relative;
          height: 500px;
        }
        
        input {
          width: 300px;
          border: none;
          position: absolute;
          top: 50%;
          left: -100%;
          transform: translateY(-50%);
          background: transparent;
        }
    <div class="input-outline">
          <input type="text" value="this a long text blablabla heheheheeheheheheh">
        </div>