How to calculate absolute position of transformed div

試著忘記壹切 提交于 2019-12-12 02:54:01

问题


When you use transform on div, absolute positioning not working as you expected anymore, and seems like it needs to be calculated manually. For instance when you want your div to be at the bottom of container you do:

div{
    position:absolute;
    bottom:0%;
}

But if you transform this div like -webkit-transform:rotateX(angle); it won't be at the bottom of container. Is places somewhere in between of container depends of its size.

I create jsfiddle to illustrate this, and also show what i'm trying to achive: http://jsfiddle.net/9NHJt/

Here's the code i use:

<div class="container"> height: 150px;
    <div class="inner"></div>
</div>

<div class="container" style="height:250px"> height: 250px;
    <div class="inner"></div>
</div>

<div class="container"> desired result
    <div class="inner" style="bottom:-19px"></div>
</div>


.container{
    margin-top:30px;
    position:relative;
    width:500px;
    height:150px;
    -webkit-perspective:1000px;
    border:1px solid black
}

.inner{
    -webkit-transform:rotateX(45deg);
    background:rgba(238, 238, 238, 0.8);
    border:1px dashed black;
    position:absolute;    
    width:100%;
    height:100%;
    bottom:0%; /* Needs to be calculated */
}

So, is there a way to fix this without javascript? Or how to calculate correct bottom position with js?


回答1:


Ok, you should add a tag : 'geometry'. First thing, remember to sine and cosine, then take a calculator : rotation around the x assis is 45 degrees
The cos of 45 it's around 0,7, then//value of cos for 45 degrees
0.7*150=106 //the height of the rectangle afther transformation
(150-106)/2 //the space remaining in the parent up and down the element divided by 2
the result is 22 and this is positive top or the negative bottom you need.

Same for the second block: (250-(0.7*250))/2 = 37.5

Remember to recalculate the value of the angle if you change it. More rounded the numbers are, more you will be accurate. Remember that calulation can be heavy for many tag.




回答2:


here is a Fiddle to check, let me know if this is what you want?

.inner{
    -webkit-transform:rotateX(45deg);
    background:rgba(238, 238, 238, 0.8);
    border:1px dashed black;
    position:absolute;    
    width:100%;
    height:100%;
    /* bottom:0%; removed */
}


来源:https://stackoverflow.com/questions/16874055/how-to-calculate-absolute-position-of-transformed-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!