我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
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;
}
这里还有更多的例子。
其他回答
响应式解决方案
如果您不需要支持IE8或更低版本,这里有一个很好的解决方案,可用于响应设计或未知尺寸。
.centered-axis-x {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
.外部{位置:相对;/*或绝对值*//*不必要的样式设置财产*/保证金:5%;宽度:80%;高度:500px;边框:1px纯红色;}.内部{位置:绝对;左:50%;顶部:50%;转换:转换(-50%,-50%);/*不必要的样式设置财产*/最大宽度:50%;文本对齐:居中;边框:1px纯蓝色;}<div class=“outer”><div class=“inner”>我总是居中<br/>无论我有多少文本、高度或宽度<br/>维度或我的父级也不相关</div></div>
这是一个JS Fiddle
线索是,剩下的:50%是相对于父对象的,而平移变换是相对于元素宽度/高度的。
这样,您就拥有了一个完全居中的元素,子元素和父元素都具有灵活的宽度。奖励:即使孩子比父母大,这也能奏效。
您也可以使用此选项垂直居中(同样,父级和子级的宽度和高度可以完全灵活(和/或未知)):
.centered-axis-xy {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
请记住,您可能还需要以转换供应商为前缀。例如-webkit转换:translate(-50%,-50%);
.center {
position: absolute
left: 50%;
bottom: 5px;
}
.center:before {
content: '';
display: inline-block;
margin-left: -50%;
}
#内容{margin:0自动;显示:表格;float:none;}<body><div><div id=“content”>我是内容</div></div></body>
这个问题的公认解决方案不适用于我的情况。。。
我正在为一些图片做字幕,我用这个解决了这个问题:
top: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
display: flex;
align-items: center;
数字{位置:相对;宽度:325px;显示:块}图标题{位置:绝对;背景:#FFF;宽度:120px;填充:20px;-webkit框阴影:0 0 30px灰色;方框阴影:0 0 30px灰色;边界半径:3px;显示:块;顶部:0;左:0;右:0;左边距:自动;右边距:自动;显示:柔性;对齐项目:居中;}<图><img src=“https://picsum.photos/325/600"><figcaption>但也一样</figcaption></figure>
我想补充一下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>