Html 如何使用相对于绝对定位输入框的 css 定位标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24677863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:14:11  来源:igfitidea点击:

How to position a label using css relative to an absolute positioned input box

htmlcss

提问by Michael Bellamy

I'm trying to position a label using only html/css relative to an absolute positioned input box.

我正在尝试仅使用 html/css 相对于绝对定位输入框来定位标签。

The html is being generated by code, and it outputs an input box like this:

html 是由代码生成的,它输出一个输入框,如下所示:

<input type="text" style="position: absolute; top: 200px; left: 200px;"></input>

The label then has a class with 4 possible values, left, top, right and bottom.

然后标签有一个包含 4 个可能值的类,左、上、右和下。

<input type="text" style="position: absolute; top: 200px; left: 200px;">
    <label class="top">Client Forename</label>
</input>

If the label is positioned right then the label needs to go to the right of the input box etc, etc.

如果标签位于右侧,则标签需要位于输入框等的右侧,等等。

What I know of CSS is that the parent normally has a position of relative, with the child as an absolute allowing the child to be positioned anywhere in relation to the parent.

我对 CSS 的了解是,父级通常具有相对位置,子级作为绝对位置,允许子级定位在与父级相关的任何位置。

But because the input is already being set to absolute, I can't work out how to achieve this.

但是因为输入已经被设置为绝对值,我不知道如何实现这一点。

Can anyone help?

任何人都可以帮忙吗?

回答by James Montagne

An inputcan't contain other element and as such can't have other elements positioned relative to it. You can however wrap both elements in a common parent and absolutely position that. Then the labelcan be positioned absolutely in relation to the parent element.

Aninput不能包含其他元素,因此不能有其他元素相对于它定位。但是,您可以将两个元素包装在一个共同的父元素中并绝对定位它。然后label可以相对于父元素绝对定位。

http://jsfiddle.net/KeW3R/1/

http://jsfiddle.net/KeW3R/1/

New HTML structure:

新的 HTML 结构:

<div style="position: absolute; left: 0; top: 0;">
    <input type="text"/>
    <label class="right">label</label>
</div>
<div style="position: absolute; left: 100px; top: 50px;">
    <input type="text"/>
    <label class="left">label</label>
</div>
<div style="position: absolute; left: 0; top: 100px;">
    <input type="text"/>
    <label class="top">label</label>
</div>
<div style="position: absolute; left: 0; top: 150px;">
    <input type="text"/>
    <label class="bottom">label</label>
</div>

CSS:

CSS:

label{
    position: absolute;
}
.right{
    top: 0;
    left: 100%;
}
.left{
    top: 0;
    right: 100%;
}
.top{
    bottom: 100%;
    left: 0;
}
.bottom{
    top: 100%;
    left: 0;
}