Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

position

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!

like image 222
Danny Avatar asked May 06 '15 20:05

Danny


People also ask

Is absolute position relative to parent?

Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.

What happens when position is absolute in CSS?

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.


1 Answers

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

like image 189
Honore Doktorr Avatar answered Sep 22 '22 07:09

Honore Doktorr