2017-05-04 2040 views
0

我有一個簡單的SVG元素,其高度和寬度等於80%。我還將元素邊距10%應用於頁面上的SVG居中。但是,由於某種奇怪的原因,保證金似乎創建了一個y-overflow,以便頁面可以滾動。這樣做沒什麼意義,因爲我應用的垂直和水平方向應該不超過100%。這裏是我的代碼:SVG元素上的多餘邊距

html, body {height: 100%;} 
 

 
* { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
svg { 
 
    margin: 10%; 
 
    height: 80%; 
 
    width: 80%; 
 
    background: #ddd; 
 
} 
 

 
svg path { 
 
    fill: none; 
 
    stroke: #000; 
 
    stroke-linejoin: round; 
 
    transition: 0.2s; 
 
}
<svg viewBox="0 0 40 40"> 
 
    <path d="M15,5 l10,0 l0,10 l10,0 l0,10 l-10,0 l0,10 l-10,0 l0,-10 l-10,0 l0,-10 l10,0 l0,-10 Z" /> 
 
</svg>

從本質上講,我希望SVG與利潤百分比爲中心的,我不想身體被滾動。

在此先感謝!

回答

0

overflow-y:hidden添加到身體以防止滾動。這是下面的代碼片段。

html, 
 
body { 
 
    height: 100%; 
 
} 
 

 
body { 
 
    overflow-y: hidden; 
 
} 
 

 
* { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
svg { 
 
    margin: 10%; 
 
    height: 80%; 
 
    width: 80%; 
 
    background: #ddd; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    margin: auto; 
 
    position:absolute; 
 
} 
 

 
svg path { 
 
    fill: none; 
 
    stroke: #000; 
 
    stroke-linejoin: round; 
 
    transition: 0.2s; 
 
}
<svg viewBox="0 0 40 40"> 
 
    <path d="M15,5 l10,0 l0,10 l10,0 l0,10 l-10,0 l0,10 l-10,0 l0,-10 l-10,0 l0,-10 l10,0 l0,-10 Z" /> 
 
</svg>

+0

謝謝!但是,這並沒有幫助,因爲我希望元素居中。 –

+0

你可以使用絕對定位?我已經編輯了絕對定位的片段。 – Santosh

+0

是的,我認爲有幾種方法可以做到這一點。但是,我更想了解爲什麼這種特定的方法不起作用。 –

1

檢查definition of margin。百分比邊際是相對於包含區塊的寬度而計算的。

因此,您設置的頂部和底部邊距太大。因此滾動。

垂直居中未知大小的元素是相當棘手。 CSS並不容易。但有一個小竅門,你可以使用as explained here

這個想法是使用100%高度的第二個元素,然後垂直居中這兩個元素,以便較小的元素(本例中爲SVG)居中。

html, body {height: 100%;} 
 

 
* { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
svg { 
 
    height: 80%; 
 
    width: 80%; 
 
    background: #ddd; 
 
    vertical-align: middle; 
 
} 
 

 
svg path { 
 
    fill: none; 
 
    stroke: #000; 
 
    stroke-linejoin: round; 
 
    transition: 0.2s; 
 
} 
 

 
.wrapper:before { 
 
    content: '\200B'; /* zero width space */ 
 
    display: inline-block; 
 
    height: 100%; 
 
    vertical-align: middle; 
 
} 
 

 
.wrapper { 
 
    text-align: center; 
 
    height: 100%; 
 
}
<div class="wrapper"> 
 

 
    <svg viewBox="0 0 40 40"> 
 
    <path d="M15,5 l10,0 l0,10 l10,0 l0,10 l-10,0 l0,10 l-10,0 l0,-10 l-10,0 l0,-10 l10,0 l0,-10 Z" /> 
 
    </svg> 
 

 
</div>