center a div (absolute position and width)

流过昼夜 提交于 2020-01-03 02:54:13

问题


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? i.e., it count my div width on page load and than set to a negative number 1/2 of your it in margin-left?


回答1:


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.




回答2:


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




回答3:


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%);  }



回答4:


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.



来源:https://stackoverflow.com/questions/16439769/center-a-div-absolute-position-and-width

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