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条回答
泛滥B
2楼-- · 2018-12-31 02:31

You can place the image in a div and add a div id and have the CSS for that div have a text-align:center

HTML:

<div id="intro_img">

    <img src="???" alt="???">

</div>

CSS :

#intro_img {
    text-align:center;
}
查看更多
与风俱净
3楼-- · 2018-12-31 02:32

This works for me:

#content {
  position: absolute; 
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  width: 100px; /* Need a specific value to work */
}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>

查看更多
裙下三千臣
4楼-- · 2018-12-31 02:33

This solution works if the element has width and height

.wrapper {
  width: 300px;
  height: 200px;
  background-color: tomato;
  position: relative;
}

.content {
  width: 100px;
  height: 100px;
  background-color: deepskyblue;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
<div class="wrapper">
  <div class="content"></div>
</div>

查看更多
登录 后发表回答