1、前言
最近在使用postcss-center的時候,不理解css水平居中為什么需要“margin-right:-50%”。

margin-right:-50%
所以給作者commit了一個Issues

commit了一個Issues
根據(jù)作者提供的鏈接,才弄清楚這個細(xì)節(jié),特此記錄一下。
2、為什么水平居中需要 margin-right: -50%;?
-
細(xì)節(jié)問題展示
首先創(chuàng)建一個test.html
<html>
<style>
body {
background: white }
section {
background: black;
color: white;
border-radius: 1em;
padding: 1em;
position: absolute;
top: 50%;
left: 50%;
/*margin-right: -50%;*/
transform: translate(-50%, -50%) }
</style>
<section>
<h1>Nicely centered</h1>
<p>This text block is vertically centered.
<p>Horizontally, too, if the window is wide enough.
</section>
<html/>
打開test.html,嘗試調(diào)整窗口大小到最窄。

打開test.html,嘗試調(diào)整窗口大小到最窄。
注釋margin-right: -50%;

注釋margin-right: -50%;
刷新瀏覽器test.html

刷新瀏覽器test.html
-
細(xì)節(jié)分析
原理分析
'left: 50%'將元素的可用寬度減少50%。因此,渲染器將嘗試渲染不超過容器寬度一半的寬度。通過'margin-right: -50%'元素的右邊距在右邊相同的數(shù)量,渲染最大寬度再次與容器的寬度相同。
結(jié)果分析
當(dāng)嘗試調(diào)整窗口大小時,窗口寬度足夠?qū)挼臅r候,您會看到每個句子都在一行上。只有當(dāng)整個句子的窗口太窄時,句子才能被分割成幾行。
當(dāng)您將窗口寬度調(diào)整是文本行的兩倍寬度時
- 'margin-right:-50%'未被注釋,您會看到每個句子都在一行上
- 'margin-right:-50%'被注釋,句子被分割成幾行。
3、最后
如果有什么疑問,可以在下面評論或者私信我。
如果您覺得有幫助,請給我點個??,謝謝。