Max Koretskyi
Max Koretskyi

Reputation: 105497

why is absolute element width limited by inline-block parent

I have the following setup:

div {
    position: relative;
    display: inline-block;
}

div div {
    position: absolute;
    top: 100%;
    background: green;
}

a {
   width: 25px;
   float: left;
}
  <div>
    some
    <div>
      <a href="">1</a>
      <a href="">2</a>
    </div>
  </div>

My question is why the div that contains a elements collapses on parent div width? I'd expect a elements to stay in one line but they wrapped. Is it expected behavior? How can I work around it?

Upvotes: 3

Views: 1024

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

I'd expect a elements to stay in one line but they wrapped. Is it expected behavior?

Yes. they're floated left, but the parent is absolute positioned so constrained from the document floats. Has no width set so the inner elements align to the available space (0) even being left-floated.

a elements are inline elements by default.
First of all you'll have to remove float from your anchors, set them rather to be inline-block. Still they're vertically positioned, to fix that set white-space: nowrap; to the parent.

div{
    display: inline-block;
    position: relative;
}

div div {
    position: absolute;
    top: 100%;
    background: green;
    white-space: nowrap; /* needed! for inner inline elements */
}

a {
   width: 25px;
   display:inline-block; /* needed just for the 25px width! (otherw. remove) */
}
<div>
    some
    <div>
      <a href="">1</a>
      <a href="">2</a>
    </div>
  </div>

Upvotes: 3

Related Questions