我正在为焦点http://jsfiddle.net/krpkm5dc/上的输入字段创建文本提示。
第一个问题是如何设置position:absolute元素的最大宽度,我找到了解决方案-display:table。

 <div class="wrapper">
    <input type="text">
    <div class="hint">
        Lorem ipsum
    </div>
</div>

.wrapper {
    position: relative;
    display: inline-block;
}
.hint {
    color: white;
    background: #333;
    position: absolute;
    top: 0;
    left: 100%;
    display: none;
    max-width: 200px;
}
input:focus ~ .hint {
    display: table;
}


但是当我尝试将其定位在右侧时,它的行为就很奇怪

.hint {
    right: 100%;
}


http://jsfiddle.net/6vxye8q5/:右侧与输入的左侧不匹配。为什么会这样呢?

最佳答案

我猜想您希望.hint元素具有与输入元素相同的宽度。

如果您希望.hint出现在输入字段的左侧,
将偏移量设置为left: -100%right: 100%

如果希望.hint出现在输入字段的右侧,
将偏移量设置为right: -100%left: 100%

为了完全理解为什么这样做,您需要阅读CSS规范,以了解如何为绝对定位的元素计算偏移量和宽度:

参考:http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width

您还可以使用边距值使.hint元素偏离输入字段,或使其略微重叠,这取决于您要对布局进行样式设置的方式。

要获得较短提示文本的缩小至适合宽度,请使用display: inline-table将文本包装在元素中,并相应地为text-align调整.hint属性。



.showLeft {
  text-align: right;
}
.showRight {
  text-align: left;
}
.wrapper {
  position: relative;
  display: inline-block;
}
input:focus ~ .hint {
  display: block;
}
.hint {
  position: absolute;
  top: 0;
  display: none;
}
.tableit {
  display: inline-table;
  text-align: left;
  color: white;
  background: #333;
}
.showLeft .hint {
  left: -100%;
  right: 100%;
}
.showRight .hint {
  text-align: right;
  right: -100%;
  left: 100%;
}

<div class="showLeft">
  <div class="wrapper">
    <input type="text">
    <div class="hint">
      <div class="tableit">
        Lorem ipsum
      </div>
    </div>
  </div>
</div>
<br>
<div class="showRight">
  <div class="wrapper">
    <input type="text">
    <div class="hint">
      <div class="tableit">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo. Proin sodales pulvinar
      </div>
    </div>
  </div>
</div>

关于html - 显示器的绝对位置:表格元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33691265/

10-12 12:52
查看更多