'Inline element's absolute child position problem
I have an inline element with relative positioning and multiline content. It also contains a child with an absolute positioning. So i want to align this child to the right position of the parent element (a code snippet below).
But the lines have different length, and child element is aligned to a shorter one of the lines.
The first question is why this happening? And the second one: is the any way to fix this problem?
.container {
max-width: 150px;
background: lightgray;
}
.parent {
background: lightblue;
position: relative;
}
.child {
position: absolute;
width: 20px;
height: 10px;
background: salmon;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
right:0;
}
<div class="container">
<span class="parent">
Looooooooooooong Text here
<div class="child"></div>
</span>
</div>
Solution 1:[1]
It does not align to the shorter line, it aligns to the last line because it appears after that line in the HTML markup.
You can set the display mode of .parent to display: inline-block; in order to give it block boundaries, it makes more sense than positionning an element absoultely in relation to a normal inline layout.
Also, .child should be a <span> as well, <div> is a block element and it is not valid to put it inside a <span> which is an inline element[1]. The browser is forgiving and letting it work but you should avoid such a situation.
[1] In HTML5 the terms "block element" and "inline element" was replaced with another model, but the prencip still applies
.container {
max-width: 150px;
background: lightgray;
}
.parent {
background: lightblue;
position: relative;
display: inline-block;
}
.child {
position: absolute;
width: 20px;
height: 10px;
background: salmon;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
right:0;
}
<div class="container">
<span class="parent">
Looooooooooooong Text Here
<span class="child"></span>
</span>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Noam |
