代码之家  ›  专栏  ›  技术社区  ›  Audun Olsen

每个浏览器对简单搜索字段的处理方式都不同

  •  0
  • Audun Olsen  · 技术社区  · 7 年前

    我正在实现一个搜索字段,它由一个输入字段和一个svg图标组成。以下是Chrome、Firefox和IE11中当前的浏览器行为

    Chrome是最理想的版本 Chrome

    火狐 Firefox

    IE11(wtf) IE11

    Here's a working demo of the code in question, hosted on codepen.

    HTML

    <div class="input-wrap">
      <input placeholder="Search…" />
      <div class="icon">
        <svg viewBox="0 0 100 100">
          <g transform="scale(4,4)">
            <path d="M2.2,9.1c0-3.8,3.1-6.9,6.9-6.9c3.8,0,6.9,3.1,6.9,6.9c0,3.8-3.1,6.9-6.9,6.9C5.3,16,2.2,12.9,2.2,9.1zM24,22.4l-7.7-7.7c1.3-1.6,1.9-3.6,1.9-5.6c0-5-4.1-9.1-9.1-9.1C4.1,0,0,4.1,0,9.1s4.1,9.1,9.1,9.1l0,0c2,0,4-0.7,5.6-1.9l7.7,7.7L24,22.4z"></path>
          </g>
        </svg>
      </div>
    </div>
    

    CSS

    * { box-sizing: border-box; }
    html { font-size: 15px; }
    
    body {
      margin: 0;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .input-wrap { position: relative; }
    
    input {
      font-size: 1rem;
      padding: 20px;
      width: 400px;
      outline: none;
      border: 1px solid black;
    }
    
    .icon {
      position: absolute;
      border: 2px solid blue;
      right: 0;
      top: 0px;
      bottom: 0px;
      padding: 10px;
    }
    
    .icon svg {
      height: 100%;
      border: 2px solid yellow;
    }
    

    蓝色边框表示svg的父级,黄色边框表示svg。Chrome根据svg内容调整svg的父级大小。Firefox使svg的父项覆盖整个搜索领域。我不知道IE在干什么。我需要统一他们的行为 像铬一样工作 ,同时保留搜索字段的一个关键特征: 不使用固定长度!所有内容都是基于rem的,这意味着如果根字体大小增加,整个搜索字段应相应缩放。 我想避免任何JS的介入。

    非常感谢您的任何建议!

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ali    7 年前

    试试下面的代码,我删除了绝对定位,添加了flexbox,并将400px的宽度移动到了父级:

    * { box-sizing: border-box; }
    html { font-size: 15px; }
    
    body {
      margin: 0;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .input-wrap { 
      position: relative; 
      display: flex;
      flex-direction: row;
      width: 400px;
    }
    
    input {
      font-size: 1rem;
      padding: 20px;
      outline: none;
      border: 1px solid black;
      display: flex;
      flex-basis: 0;
      flex-grow: 1;
      max-width: 100%;
    }
    
    .icon {
      border: 2px solid blue;
      right: 0;
      top: 0px;
      bottom: 0px;
      padding: 10px;
      display: inline-flex;
      align-items: center;
    }
    
    .icon svg {
      height: 100%;
      border: 2px solid yellow;
      height: 2rem;
    }
    
    推荐文章