这是一个旧的Q,但是没有flexbox或position absolute的现代解决方案是这样的。
margin-left: 50%;
transform: translateX(-50%);
.outer {
border: 1px solid green;
margin: 20px auto;
width: 20%;
padding: 10px 0;
/* overflow: hidden; */
}
.inner {
width: 150%;
background-color: gold;
/* Set left edge of inner element to 50% of the parent element */
margin-left: 50%;
/* Move to the left by 50% of own width */
transform: translateX(-50%);
}
<div class="outer">
<div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>
</div>
那为什么行得通呢?
乍一看,似乎我们向右移动了50%,然后又向左移动了50%。那将导致零位移,那又如何呢?
但是50%并不相同,因为上下文很重要。如果使用相对单位,则边距将作为父元素宽度的百分比计算,而变换将是相对于同一元素的50%。
在添加CSS之前,我们有这种情况
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E |
+-----------------------------------------------------------+
| |
+-------------------------------------------+
随着增加的风格,margin-left: 50%
我们有
+-------------------------------------------+
| Parent element P of E |
| |
| +-----------------------------------------------------------+
| | Element E |
| +-----------------------------------------------------------+
| | |
+---------------------|---------------------+
|========= a ========>|
a is 50% width of P
然后transform: translateX(-50%)
移回左侧
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E | |
+-----------------------------------------------------------+
|<============ b ===========| |
| | |
+--------------------|----------------------+
|========= a =======>|
a is 50% width of P
b is 50% width of E
不幸的是,这仅适用于水平居中,因为边距百分比计算始终相对于宽度。即不仅margin-left
和margin-right
,而且还margin-top
和margin-bottom
相对于宽度被计算。
浏览器兼容性应该没问题:https :
//caniuse.com/#feat=transforms2d