问题描述
我使用下面的css以绝对位置居中我的div:
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.
现在我必须使用相同的CSS,但对于我的div没有固定宽度和因为它使用响应式布局。
Now i have to use this same css but for my div which has no fixed width and height, as it uses responsive layouts.
我只想知道是否有任何最简单的方法来设置我的div宽度动态在css通过javascript等等?即在页面加载时计数我的div宽度,而在margin-left中设置为它的负数1/2?
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?
推荐答案
您可以将固定
或定位元素设置
正中
和 left
到 0
,然后 margin-left
& margin-right
到 auto
,就好像你以 static
定位元素。
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%;
}
这篇关于center a div(绝对位置和宽度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!