我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
一个简单的方法,对我来说,可以将一个未知宽度的块水平居中:
<div id="wrapper">
<div id="block"></div>
</div>
#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
#block {
display: inline-block;
}
文本对齐属性可以添加到#block规则集,以独立于块的对齐方式对齐其内容。
这在Firefox、Chrome、Internet Explorer、Edge和Safari的最新版本上有效。
其他回答
您可以将图像放置在一个div中,添加一个div id,并让该div的CSS具有文本align:center:
HTML格式:
<div id="intro_img">
<img src="???" alt="???">
</div>
CSS:
#intro_img {
text-align: center;
}
响应式解决方案
假设div中的元素是另一个div。。。
此解决方案运行良好:
<div class="container">
<div class="center"></div>
</div>
容器可以是任何大小(必须是相对位置):
.container {
position: relative; /* Important */
width: 200px; /* Any width */
height: 200px; /* Any height */
background: red;
}
元素(div)也可以是任何大小(必须小于容器):
.center {
position: absolute; /* Important */
top: 50%; /* Position Y halfway in */
left: 50%; /* Position X halfway in */
transform: translate(-50%,-50%); /* Move it halfway back(x,y) */
width: 100px; /* Any width */
height: 100px; /* Any height */
background: blue;
}
结果将是这样的。运行代码段:
.容器{位置:相对;宽度:200px;高度:200px;背景:红色;}.中心{位置:绝对;顶部:50%;左:50%;转换:转换(-50%,-50%);宽度:100px;高度:100px;背景:蓝色;}<div class=“container”><div class=“center”></div></div>
我觉得这很有帮助。
这里有一个有用的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)
});
};
HTML格式:
<div class="wrapper">
<div class="inner">
content
</div>
</div>
CSS:
.wrapper {
position: relative;
width: 200px;
height: 200px;
background: #ddd;
}
.inner {
position: absolute;
top: 0; bottom: 0;
left: 0; right: 0;
margin: auto;
width: 100px;
height: 100px;
background: #ccc;
}
这里还有更多的例子。
尽量不要使用CSS的阴暗面。避免使用负值作为边距。我知道有时候你会被迫做一些糟糕的事情,比如左边距:-450px,但你可能会做一些右边距:450px。这只是我的工作方式。