Charles
Charles

Reputation: 11778

How to make list fits content when using position absolute

How can I make this list fit his content when it has position absolute to parent?

div {
  width: 100px;
  position: relative;
}
ul {
  position: absolute;
}
li {
  background: red;
}
<div>
  <ul>
    <li>easdas da dsad asd as</li>
    <li>fdsf dsf sd</li>
  </ul>
</div>

EDIT: I want to achieve this (realised by adding width: 140px; to ul): enter image description here

EDIT2: Is there a solution without white-space:nowrap in order to be able to set a max-width to li?

Upvotes: 1

Views: 281

Answers (4)

Hatora
Hatora

Reputation: 76

Not exactly sure what you're asking but I think you're wanting to add the property: left: 0; inside the ul element and setting your margin and padding to zero so your elements will fit inside your div though you might want to add width: 100%; to the unordered list so it'll be fixed to the parent element.

EDIT:

This should work if you want to break the context when the text reaches your width though if you dont want to see the text on the second line you could specify height.

div {
  width: 100px;
  position: relative;
}
ul {
  position: absolute;
}
li {
  background: red;
  max-width: 140px;
}
<div>
  <ul>
    <li>easdas da dsad asd as</li>
    <li>fdsf dsf sd</li>
  </ul>
</div>

Upvotes: 0

EugenSunic
EugenSunic

Reputation: 13703

div {
    width: 100%;
    position: relative;
}
ul {
    position: absolute;
}
li {
    background: red;
}

You can do this by chaging the width to 100%

Upvotes: 0

Jordan Davis
Jordan Davis

Reputation: 1520

Take out the 100px in the CSS on the div tag.

Live Example --> https://jsfiddle.net/431u1doe/

//CSS

div {
  position: relative;
}
ul {
  position: absolute;
}
li {
  background: red;
}

Upvotes: 0

j08691
j08691

Reputation: 207901

You can add white-space:nowrap to the list item rules:

div {
  width: 100px;
  position: relative;
}
ul {
  position: absolute;
}
li {
  background: red;
  white-space:nowrap;
}
<div>
  <ul>
    <li>easdas da dsad asd as</li>
    <li>fdsf dsf sd</li>
  </ul>
</div>

Upvotes: 2

Related Questions