How do I centre absolutely positioned content of unknown width?

半城伤御伤魂 提交于 2019-11-30 00:06:26

Either use JavaScript to calculate the width and move it,

use a CSS hack to move the element right and left by 50%,

or don't absolutely position it.


This answer is incredibly short, but it is to the point. If you require something to be centralised (meaning you would like the browser to determine where the centre point is, and position it there), then you can't use absolute positioning - because that takes away control from the browser.


To fade the paintings in over each other I need to position them 'absolute' to stop them from stacking.

This is where your problem lies. You have assumed that you need absolute positioning for the wrong reason.

If you are experiencing problems placing elements on top of each other, wrap the images in an absolutely positioned container which is 100% width and has text-align: center


If you do feel that absolute positioning is necessary, the following hack can be used to achieve your desired results:

div {
    position: absolute;
    /* move the element half way across the screen */
    left: 50%;
    /* allow the width to be calculated dynamically */
    width: auto;
    /* then move the element back again using a transform */
    transform: translateX(-50%);
}

Obviously the above hack has a terrible code smell, but it works on some browsers. Be aware: this hack is not necessarily obvious to other developers, or other browsers (especially IE or mobile).

Samec Hadra

Pushing the element left by 50% of its width and then translating it horizontally by 50% has worked for me.

.element {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
} 

I found the concept in the following link, and then I translated to fit my horizontal align needs: https://gist.github.com/colintoh/62c78414443e758c9991#file-douchebag-vertical-align-css

To go off of Samec's answer, you can also use this to center an absolute position element vertically and horizontally of unknown dimensions:

#viewer_div {
  position: relative;
}
#viewer_div img {
  position: absolute;
  left: 50%;
  top: 0%;
  transform: translate(-50%, 50%);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!