How to center absolutely positioned element in div

2018-12-31 02:05发布

I need to place a div (with position:absolute;) element in the center of my window. But I am having problems doing so, because the width is unknown.

I tried this. But it needs to be adjusted as the width is responsive.

.center {
  left: 50%;
  bottom:5px;
}

Any ideas?

27条回答
荒废的爱情
2楼-- · 2018-12-31 02:07

Heres a useful jQuery plugin to do this. Found here. I don't think it's possible purely with CSS

/**
 * @author: Suissa
 * @name: Absolute Center
 * @date: 2007-10-09
 */
jQuery.fn.center = function() {
    return this.each(function(){
            var el = $(this);
            var h = el.height();
            var w = el.width();
            var w_box = $(window).width();
            var h_box = $(window).height(); 
            var w_total = (w_box - w)/2; //400
            var h_total = (h_box - h)/2;
            var css = {"position": 'absolute', "left": w_total+"px", "top":
h_total+"px"};
            el.css(css)
    });
};
查看更多
余生无你
3楼-- · 2018-12-31 02:09

HTML:

<div class="wrapper">
    <div class="inner">
        content
    </div>
</div>

CSS:

.wrapper {
    position: relative;

    width: 200px;
    height: 200px;

    background: #ffffd;
}

.inner {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;

    width: 100px;
    height: 100px;

    background: #ccc;
}

This and more examples here

查看更多
何处买醉
4楼-- · 2018-12-31 02:10

I have used similar solution:

#styleName {
    position: absolute;
    margin-left: -"X"px;
}

Where "X" is half of the width of a div I want to display. Works fine for me in all browsers.

查看更多
公子世无双
5楼-- · 2018-12-31 02:14

Searching for an solution I got answers above and could make content centered with Matthias Weiler answer but using text-align.

#content{
  position:absolute;
  left:0;
  right:0;
  text-align: center;
}

Worked with chrome and Firefox.

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 02:14

Works on any random unknown width of the absolute positioned element you want to have in the centre of your container element.

Demo

<div class="container">
  <div class="box">
    <img src="https://picsum.photos/200/300/?random" alt="">
  </div>
</div>

.container {
  position: relative;
  width: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
查看更多
听够珍惜
7楼-- · 2018-12-31 02:14

This worked for me :

<div class="container><p>My text</p></div>

.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
查看更多
登录 后发表回答