如何在div中对绝对定位元素进行居中?

如何在div中对绝对定位元素进行居中?

我要放一个div(与position:absolute;)元素在我的窗口中间。但我在做这件事上有问题,因为宽度未知.

我试过这个。但它需要调整,因为宽度是响应。

.center {
  left: 50%;
  bottom:5px;}

有什么想法吗?


智慧大石
浏览 3733回答 3
3回答

婷婷同学_

<body>&nbsp; <div style="position: absolute; left: 50%;">&nbsp; &nbsp; <div style="position: relative; left: -50%; border: dotted red 1px;">&nbsp; &nbsp; &nbsp; I am some centered shrink-to-fit content! <br />&nbsp; &nbsp; &nbsp; tum te tum&nbsp; &nbsp; </div>&nbsp; </div></body>

慕哥6287543

这对我有用:#content {&nbsp; position: absolute;&nbsp;&nbsp; left: 0;&nbsp;&nbsp; right: 0;&nbsp;&nbsp; margin-left: auto;&nbsp;&nbsp; margin-right: auto;&nbsp;&nbsp; width: 100px; /* Need a specific value to work */}<body>&nbsp; <div>&nbsp; &nbsp; <div id="content">&nbsp; &nbsp; &nbsp; I'm the content&nbsp; &nbsp; </div>&nbsp; </div></body>

鸿蒙传说

响应解这里有一个很好的解决方案用于响应性设计或未知尺寸总体而言如果你不需要支持IE8和更低的。.centered-axis-x&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;absolute; &nbsp;&nbsp;&nbsp;&nbsp;left:&nbsp;50%; &nbsp;&nbsp;&nbsp;&nbsp;transform:&nbsp;translate(-50%,&nbsp;0);}.outer {&nbsp; &nbsp; position: relative; /* or absolute */&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /* unnecessary styling properties */&nbsp; &nbsp; margin: 5%;&nbsp; &nbsp; width: 80%;&nbsp; &nbsp; height: 500px;&nbsp; &nbsp; border: 1px solid red;}.inner {&nbsp; &nbsp; position: absolute;&nbsp; &nbsp; left: 50%;&nbsp; &nbsp; top: 50%;&nbsp; &nbsp; transform: translate(-50%, -50%);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /* unnecessary styling properties */&nbsp; &nbsp; max-width: 50%;&nbsp; &nbsp; text-align: center;&nbsp; &nbsp; border: 1px solid blue;}<div class="outer">&nbsp; &nbsp; <div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div></div>这是一个JS Fiddle线索是,left: 50%是相对于父级的,而translate转换相对于元素的宽度/高度。这样,您就有了一个完美的居中元素,子元素和父元素都具有灵活的宽度。奖励:即使孩子比父母大,这也是可行的。您也可以用它垂直对中(同样,父级和子级的宽度和高度可以完全灵活(和/或未知):.centered-axis-xy&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;absolute; &nbsp;&nbsp;&nbsp;&nbsp;left:&nbsp;50%; &nbsp;&nbsp;&nbsp;&nbsp;top:&nbsp;50%; &nbsp;&nbsp;&nbsp;&nbsp;transform:&nbsp;translate(-50%,-50%);}记住你可能需要transform供应商的前缀也是。例如-webkit-transform: translate(-50%,-50%);
打开App,查看更多内容
随时随地看视频慕课网APP