简体   繁体   中英

center a div (absolute position and width)

i use below css to center my div with absolute position:

#mydiv {
    position:absolute;
    top: 50%;
    left: 50%;
    width: 121px;
    height: 121px;
    margin-top: -60.5px; /*set to a negative number 1/2 of your height*/
    margin-left: -60.5px; /*set to a negative number 1/2 of your width*/
}

It works like magic. But as you can notice, it has fixed width and height.

Now i have to use this same css but for my div which has no fixed width and height, as it uses responsive layouts.

I just want to know is there any simplest way to set my div width dynamically in css by javascript or so? ie, it count my div width on page load and than set to a negative number 1/2 of your it in margin-left?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM