Center Align on a Absolutely Positioned Div

2019-01-16 06:08发布

div#thing {
  position: absolute;
  top: 0px;
  z-index: 2;
  margin: 0 auto;
}

<div id="thing">
   <p>text text text with no fixed size, variable font</p>
</div>

The div is at the top, but I can't center it with <center> or margin: 0 auto;

标签: html css xhtml
6条回答
beautiful°
2楼-- · 2019-01-16 06:42

I was having the same issue, and my limitation was that i cannot have a predefined width. If your element does not have a fixed width, then try this

div#thing 
{ 
  position: absolute; 
  top: 0px; 
  z-index: 2; 
  left:0;
  right:0;
 }

div#thing-body
{
  text-align:center;
}

then modify your html to look like this

<div id="thing">
 <div id="thing-child">
  <p>text text text with no fixed size, variable font</p>
 </div>
</div>
查看更多
放我归山
3楼-- · 2019-01-16 06:48

Your problem may be solved if you give your div a fixed width, as follows:

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}
查看更多
别忘想泡老子
4楼-- · 2019-01-16 06:49

If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

Remember that in order to position an element absolutely, the parent element must be positioned relatively.

查看更多
迷人小祖宗
5楼-- · 2019-01-16 06:51
div#thing
{
    position: absolute;
    width:400px;
    right: 0;
    left: 0;
    margin: auto;
}
查看更多
forever°为你锁心
6楼-- · 2019-01-16 06:56

I know I'm late to the party, but I thought I would provide an answer here for people who need to horizontally position an absolute item, when you don't know its exact width.

Try this:

// Horizontal example.
div#thing {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

The same technique can also be applied, for when you might need vertical alignment, simply by adjusting the properties like so:

// Vertical example.
div#thing {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
查看更多
走好不送
7楼-- · 2019-01-16 07:08

Yes:

div#thing { text-align:center; }
查看更多
登录 后发表回答