How to fix a position: relative when using a translation

it seems like using transform: translateY(1px); also forces the element to get an extra position: relative; -behaviour.

Is there any way to do this?

Here is an example on codepen.io .

I would like to position the white box absolutely on green, and not on the parent (red).

+6
source share
3 answers

One option would be to offset / negate parental positioning by wrapping the element around #three (in this case, I added the .displacement element).

Absolutely place this wrapping element and place it to cover the parent (using top: 0 / right: 0 / bottom: 0 / left: 0 ). Then extrude the element with negative translation values ​​relative to the parent.

 <div class="displacement"> <div id="three"></div> </div> 
 .displacement { -webkit-transform: translateY(-25px) translateX(-25px); transform: translateY(-25px) translateX(-25px); position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 200%; height: 200%; } 

In this case, the #three element #three positioned absolutely relative to #one , and the portable positioning of the parent #two effectively shifted.

Updated example

 .displacement { -webkit-transform: translateY(-25px) translateX(-25px); transform: translateY(-25px) translateX(-25px); position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 200%; height: 200%; } #three { background-color: white; height: 25px; width: 25px; position: absolute; left: 0; bottom: 0; } 
+3
source

position:absolute (from moz) Do not leave space for the element. Instead, place it at a predetermined position relative to its nearest located ancestor or to the containing block. Absolutely positioned fields can have fields; they are not compressed with any other fields.

so in your case, the closest ancestor will always be #two , which does not inherit any position property, just the default position: static; ...


if you gave #two position:relative// or absolute and positioned it with top: and left: it might have been easier to place #three: http://codepen.io/maio/pen/qEMJpY

0
source

A non-standard workaround is used here, but it works for your existing markup.

Change your #two CSS to a #two -element by adding the following styles:

 #two::before { content: ''; display: block; } 

Updated CodePen


If you don't change your markup, another solution is to use JavaScript to make the three children of the one element:
 document.querySelector('#one').appendChild(document.querySelector('#three')); 

However, it will no longer inherit any styles from the two element, as shown in this CodePen .

Here's an interesting read that confirms the "element conversion force-add position: relative.": Http://meyerweb.com/eric/thoughts/2011/09/12/un-fixing-fixed-elements-with-css-transforms/

Not only this, but also affects the elements of a fixed position, which does not make much sense.

0
source

Source: https://habr.com/ru/post/983542/


All Articles