Bu eski bir Q, ancak flexbox veya mutlak pozisyonu olmayan modern bir çözüm böyle çalışır.
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>
Peki neden çalışıyor?
İlk bakışta% 50 sağa, sonra% 50 tekrar sola kaydığımız anlaşılıyor. Bu sıfır kaymaya neden olur, ne olacak?
Ancak% 50 aynı değildir, çünkü bağlam önemlidir. Eğer göreli birimlerini kullanan ise, bir kenar bölgesinin genişliğinin yüzdesi olarak hesaplanır üst % 50 bağlı olacaktır dönüşümü ise, elemanın aynı öğeye .
CSS eklemeden önce bu durum var
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E |
+-----------------------------------------------------------+
| |
+-------------------------------------------+
İlave tarzı ile margin-left: 50%sahip olduğumuz
+-------------------------------------------+
| Parent element P of E |
| |
| +-----------------------------------------------------------+
| | Element E |
| +-----------------------------------------------------------+
| | |
+---------------------|---------------------+
|========= a ========>|
a is 50% width of P
Ve transform: translateX(-50%)sola doğru kayıyor
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E | |
+-----------------------------------------------------------+
|<============ b ===========| |
| | |
+--------------------|----------------------+
|========= a =======>|
a is 50% width of P
b is 50% width of E
Maalesef bu sadece yatay merkezleme için işe yarar çünkü marjin yüzdesi hesaplaması her zaman genişliğe göredir. Yani sadece margin-leftve margin-rightaynı zamanda margin-topvemargin-bottom genişliği ile ilgili olarak hesaplanır.
Tarayıcı uyumluluğu sorun olmamalı:
https://caniuse.com/#feat=transforms2d