janek37
janek37

Reputation: 572

Position absolute related to an inline element

I want to have a word directly above another word in some longer text.

This fiddle doesn't achieve it (checked in Firefox and Chrome), "bar" position is not related to "foo", even though "foo" has position: fixed. To make things weirder, when I inspect the "bar" element in Firefox and turn off position: absolute and then turn it on again, "bar" moves above "foo", so it's clearly some undefined behavior.

Here's the fiddle's code:

.node {
  position: relative;
  display: inline;
}

.tip {
  position: absolute;
  top: -12px;
  font-size: 9px;
  line-height: 12px;
  color: #c83025;
}
aaaaaaa
<div class="node">
  foo
  <div class="tip">bar</div>
</div>

Upvotes: 2

Views: 3970

Answers (2)

Johannes
Johannes

Reputation: 67748

Use display: inline-block; on .node (inline elements can't have position: relative, inline-blocks can)

.node {
    position: relative;
    display: inline-block;
}

.tip {
    position: absolute;
    top: -12px;
    font-size: 9px;
    line-height: 12px;
    color: #c83025;
    left:0;
    right:0;
    text-align: center;
}
aaaaaaa
<div class="node">
  foo
  <div class="tip">bar</div>
</div>

BTW: I added some code to center the absolutely positioned word in relation to its "parent word".

Upvotes: 2

Vadim Ovchinnikov
Vadim Ovchinnikov

Reputation: 14012

You can achieve this via position: relative and negative margin-left and top. Also instead of top you can use transform: translateY with some percentage like transform: translateY(-100%).

Demo:

body {
  /* just for demo */
  margin: 20px;
}

.node {
  position: relative;
  display: inline;
}

.tip {
  /* don't move to next line but allow margin-setting */
  display: inline-block;
  position: relative;
  color: #c83025;
  top: -15px;
  margin-left: -25px;
}
aaaaaaa
<div class="node">
  foo
  <div class="tip">bar</div>
</div>
some other text

Upvotes: 0

Related Questions