我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
我想补充一下bobince的回答:
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</body>
改进:///这使得水平滚动条不会在居中的div中出现大元素。
<body>
<div style="width:100%; position: absolute; overflow:hidden;">
<div style="position:fixed; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</div>
</body>
其他回答
我想补充一下bobince的回答:
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</body>
改进:///这使得水平滚动条不会在居中的div中出现大元素。
<body>
<div style="width:100%; position: absolute; overflow:hidden;">
<div style="position:fixed; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</div>
</body>
这里有一个有用的jQuery插件来实现这一点。我在这里找到的。我不认为纯粹使用CSS是可能的。
/**
* @author: Suissa
* @name: Absolute Center
* @date: 2007-10-09
*/
jQuery.fn.center = function() {
return this.each(function(){
var el = $(this);
var h = el.height();
var w = el.width();
var w_box = $(window).width();
var h_box = $(window).height();
var w_total = (w_box - w)/2; //400
var h_total = (h_box - h)/2;
var css = {"position": 'absolute', "left": w_total + "px", "top":
h_total + "px"};
el.css(css)
});
};
Flexbox可用于对绝对定位的div。
display: flex;
align-items: center;
justify-content: center;
.相对{宽度:275px;高度:200px;背景:皇家蓝;颜色:白色;边距:自动;位置:相对;}.绝对块{位置:绝对;高度:36px;背景:橙色;填充:0px 10px;底部:-5%;边框:1px实心黑色;}.居中文本{显示:柔性;对齐内容:中心;对齐项目:居中;盒子阴影:1px 2px 10px 2px rgba(0、0、0和0.3);}<div class=“relative center text”>相对块(Relative Block)绝对块</div></div>
在寻找解决方案时,我得到了前面的答案,可以将内容以Matthias Weiler的答案为中心,但使用文本对齐:
#content{
position: absolute;
left: 0;
right: 0;
text-align: center;
}
它与谷歌Chrome和Firefox配合使用。
我使用了类似的解决方案:
#styleName {
position: absolute;
margin-left: -"X"px;
}
其中“X”是要显示的div宽度的一半。它适用于所有浏览器。