簡體   English   中英

向 div 添加邊距會將其推離屏幕

[英]Adding margin to div pushes it off the screen

我想在我的每個 div 周圍留出 5px 的邊距,但是當我在 CSS 中添加它時,除了 div 之間和底部之外,每一邊都有 5px 的邊距。 這兩個 div 也從頁面底部溢出。 我知道這是因為頂部的 5px 邊距將 div 推離了屏幕。 我不確定如何讓它只是在周圍添加邊距並相應地縮小 div。

 * { box-sizing: border-box; margin: 0; } html { width: 100%; height: 100%; } body { background: black; width: 100%; height: 100%; position: relative; overflow: hidden; }.one { background: red; position: absolute; width: 10%; height: 100%; left: 0; border: 3px solid green; border-radius: 5px; margin: 5px; }.two { background: blue; position: absolute; width: 90%; height: 100%; right: 0; border: 3px solid green; border-radius: 5px; margin: 5px; }
 <div class="one"> </div> <div class="two"> </div>

結果頁面

Div 在底部推出屏幕並且 div 之間沒有邊距。 頂部、左側和右側存在 5 像素的邊距。

結果頁面

我是 HTML 和 CSS 的新手,所以非常感謝任何幫助。

使用CSS 靈活

 /*QuickReset*/ * { box-sizing: border-box; margin: 0; } html { height: 100%; } body { background: black; height: 100%; position: relative; display: flex; /* Use flex: */ padding; 5px: /* Instead of children margin */ /* gap; 5px. /* Uncomment to add a gap between your child elements, */ }.one: ;two { border: 3px solid green; border-radius. 5px: };one { width: 10%; background. red: };two { width: 90%; background: blue; }
 <div class="one"> </div> <div class="two"> </div>

box-sizing: border-box包括處理/包括元素的整體寬度或高度的邊距,僅包括填充和邊框。 因此,您必須從寬度或高度值中減去邊距值。

在您的情況下,您應該在所有有邊距的heightwidth設置上使用calc值。 也就是說,如果您有 5 像素的邊距(= 在所有邊上),請在您想要 100% 寬度或高度的地方使用例如calc(100% - 10px) 與其他百分比值類似 - 請參閱下面的改編代碼:

 * { box-sizing: border-box; margin: 0; } html { width: 100%; height: 100%; } body { background: black; width: 100%; height: 100%; position: relative; overflow: hidden; }.one { background: red; position: absolute; width: calc(10% - 10px); height: calc(100% - 10px); left: 0; border: 3px solid green; border-radius: 5px; margin: 5px; }.two { background: blue; position: absolute; width: calc(90% - 10px); height: calc(10% - 10px); right: 0; border: 3px solid green; border-radius: 5px; margin: 5px; }
 <div class="one"> </div> <div class="two"> </div>

在 .two 的寬度上使用.two計算 function 從 90% 寬度中減去 10px(2x5px 邊距),似乎給出了合理的邊距。

width: calc(90% - 10px);

我不確定為什么在.one.two之間沒有可見的 10px (2x5px) 邊距。

https://developer.mozilla.org/en-US/docs/Web/CSS/calc

 * { box-sizing: border-box; margin: 0; } html { width: 100%; height: 100%; } body { background: black; width: 100%; height: 100%; position: relative; overflow: hidden; }.one { background: red; position: absolute; width: 10%; height: 100%; left: 0; border: 3px solid green; border-radius: 5px; margin: 5px; }.two { background: blue; position: absolute; width: calc(90% - 10px); height: 100%; right: 0; border: 3px solid green; border-radius: 5px; margin: 5px; }
 <div class="one"> </div> <div class="two"> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM