Danny
Danny

Reputation: 599

CSS Positioned Absolute Element, automatic width outside of parent's bounds?

So, I have my parent element positioned relative, in order to allow a tooltip element to be positioned absolute inside, at the top of it. I am aware that you are required to add "left: 0, right: 0", so that the width of the element is still able to be set to auto, which I have done. However, my parent element has a fixed width, which the tooltip becomes restrained to, so the auto width cannot go outside of it, is there any way around this?

CSS:

.parent {
  position: relative;
  width: 100px;
  height: 100px;
}

.tooltip {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  text-align: center;
  width: auto;
  padding: 5px 10px;
}

Elements:

<div class="parent">
  <div class="tooltip">Text goes here</div>
</div>

No JS please, looking for a CSS solution, thanks!

Upvotes: 50

Views: 60445

Answers (5)

Gaurav Patil
Gaurav Patil

Reputation: 1382

Use width auto with white-space: nowrap; and position absolute

.class {
  white-space: nowrap;
  width: auto;
  position: absolute;
}

Upvotes: 1

Joe Koker
Joe Koker

Reputation: 961

I believe the best solution for this issue is not setting left, right or white-space: nowrap but we have a new value for width property max-content... so just add the width: max-content;(this one works with max-width as well)

demo: http://jsfiddle.net/qLgw8bxu/

support: https://caniuse.com/#search=max-content

.tooltip {
 background-color: blue;
 position: absolute;
 text-align: center;
 padding: 5px 10px;

 width: max-content;
}

Upvotes: 38

Steven Vachon
Steven Vachon

Reputation: 3980

If .parent can be made inline, you could make .tooltip render as a table and it will autosize to fit its contents, but unlike with the use of white-space:nowrap, it would also support a max-width.

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

.tooltip {
  position: absolute;
  display: table;
  top: 0;
  left: 0;
  text-align: center;
  padding: 5px 10px;
  max-width: 200px;
}

Upvotes: 5

Honore Doktorr
Honore Doktorr

Reputation: 1625

Not setting both left and right on .tooltip, and setting white-space: nowrap should do it:

.tooltip {
  position: absolute;
  top: 0;
  left: 0;
  margin: 0 auto;
  text-align: center;
  width: auto;
  padding: 5px 10px;
  white-space: nowrap;
}

Working example.

You'd need to use this solution to center an absolute element. It does require an additional element, though. Demo

Upvotes: 102

Jasper van Amerongen
Jasper van Amerongen

Reputation: 11

I haven't seen this problem before, but what I think is going on, is that width: auto; automatically inherits the properties of its parent. So either you have to put a number in (width: 50px;) or a percentage (width: 50%).

Upvotes: 1

Related Questions