62
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

css position:fixedで縦横中央に要素を配置する

Last updated at Posted at 2016-09-12

translateを使う方法

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

元記事はこちら:
http://stackoverflow.com/a/26962247/5209556

元記事によると、translateを使うと3Dアクセラレーションが有効になるため、divの中の文字がぼやける、そこで対策として-webkit-font-smoothingを使えと書いてある。
確かにMacのChromeでぼやける現象が発生した。

-webkit-font-smoothing: none;
-webkit-font-smoothing: antialiased;
-webkit-font-smoothing: subpixel-antialiased; /* Safari での Default値 */

いずれを指定しても直らなかった。

calcを使う方法

.center{
    position: fixed;
    height: 50px;
    width: 50px;
    background:red;
    top:calc(50% - 50px/2);
    left:calc(50% - 50px/2);
}

jQueryを使う方法

$.fn.center = function() {
    this.css({
        'position': 'fixed',
        'left': '50%',
        'top': '50%'
    });
    this.css({
        'margin-left': -this.outerWidth() / 2 + 'px',
        'margin-top': -this.outerHeight() / 2 + 'px'
    });

    return this;
}
62
49
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
62
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?