Search code examples
htmlcsscss-positiontransformbem

css transform() center positioning of a popup window issue


Found an interesting way to make centered popup window ( http://www.w3.org/Style/Examples/007/center ) in application. Simple and good looking in code ( http://jsfiddle.net/babaca/6rwL0v0c/22/ ).

html

<div class="__holder">
    <div class="__box">
        <h2>Some header</h2>
        Some bunch of content etc
    </div>
</div>

css

.__holder {
    position: fixed;
    z-index: 15000;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;

    width: 100%;
    height: 100%;

    background-color: rgba(0,0,0,.5);
}
.__box {
    position: absolute;
    z-index: 16000;
    top: 50%;
    left: 50%;

    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
    margin-right: -50%;
    padding: 0;

    transform: translate(-50%, -50%);

    -webkit-border-radius: 6px;
       -moz-border-radius: 6px;
            border-radius: 6px;
    background-color: #fff;
    -webkit-box-shadow: 0 0 18px 3px rgba(0, 0, 0, .07);
       -moz-box-shadow: 0 0 18px 3px rgba(0, 0, 0, .07);
            box-shadow: 0 0 18px 3px rgba(0, 0, 0, .07);

    padding: 29px;
}

The only problem with render: depending on zoom level of the browser window, there is or horizontal or vertical sides are not sharp, smoothed/blured between 2 pixels... (chrome Version 39.0.2171.95 m , firefox 34.0.5 ) Here is an example(with smoothed left and right sides of the window):

enter image description here

As I figured out it is responsibility of the transform: translate(-50%, -50%) line. Anyone have met the same problem? Any solutions?


Solution

  • Well, this is indeed a nice solution as it doesn't require you to know the width and height of positioning container. If you knew them you could just replace transform with apropriate negative margins:

    margin-left: -90px; // half of the popup width
    margin-top: -45px; // half of the popup height
    

    Here's the fiddle, see if those issues still appear: http://jsfiddle.net/bcbpc6ey/

    If they do, than the problem is probably caused by internal browser scaling algorithm and there is nothing you can do, because thats how the browser works.

    However, if problem dissapears after switching transform to margins than you have probably experienced some antyaliasing issues that were caued by moving the rendering of your popup to GPU. Since transform is one of commonly known hardware accelerated CSS property, to make it run smooth browsers often move such elements into a separate layer that is than being handled entirely by GPU which is faster, but often causes some artifacts (mostly visible on fonts and scaled elements).