center a div (absolute position and width)

核能气质少年 提交于 2019-12-07 02:14:25

You can center a fixed or absolute positioned element setting right and left to 0, and then margin-left & margin-right to auto as if you were centering a static positioned element.

#example {
    position: absolute;
    /* center the element */
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    /* give it dimensions */
    min-height: 10em;
    width: 90%;
}

See this example working on this fiddle.

use to

display table-cell

as like this

Css

.parent{
    display:table-cell;
    width:400px;
    text-align:center;
    border:solid 1px red;
    vertical-align:middle;
    height:400px;

}
.child{

    display:inline-block;
    background:green;
}

HTML

    <div class="parent">

    <div class="child">i m child div</div>

</div>

Demo

I also had this problem trying to center captions of varying lengths in a slideshow.

To center an absolute positioned element that has a dynamic width you can use transform: translateX. With prefixes this works in most modern browsers. Like so:

div {
  width: auto;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);  }

Assign a class to all the divs that you want positioned like that, and then just select all of them and do the calculations.

$("body").find(".center").each(function() {
    $(this).css({
        "margin-left": "-" + ( $(this).width()/2 ) + "px",
        "margin-top": "-" + ( $(this).height()/2 ) + "px"
    });
});

Though, beware that this is a bad way of doing things, mainly because it's slow, your containers are not flexible and if you don't wait for the centering you may have flashes of unformatted content.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!