Reputation: 541
I'm trying to position a label using only html/css relative to an absolute positioned input box.
The html is being generated by code, and it outputs an input box like this:
<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.
<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.
But because the input is already being set to absolute, I can't work out how to achieve this.
Can anyone help?
Upvotes: 4
Views: 47487
Reputation: 78670
An input
can'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 label
can be positioned absolutely in relation to the parent element.
New HTML structure:
<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:
label{
position: absolute;
}
.right{
top: 0;
left: 100%;
}
.left{
top: 0;
right: 100%;
}
.top{
bottom: 100%;
left: 0;
}
.bottom{
top: 100%;
left: 0;
}
Upvotes: 15