我想在我的每個 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 之間沒有邊距。存在頂部、左側和右側的 5px 邊距。

我是 HTML 和 CSS 的新手,因此非常感謝任何幫助。
uj5u.com熱心網友回復:
使用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>
uj5u.com熱心網友回復:
box-sizing: border-box不包括處理/包括元素整體寬度或高度中的邊距,僅包括填充和邊框。因此,您必須從寬度或高度值中減去邊距值。
在您的情況下,您應該calc在所有height和width有邊距的設定上使用值。即,如果您有 5px 的邊距(= 在所有邊上),例如calc(100% - 10px)在您想要 100% 寬度或高度的地方使用。與其他百分比值類似 - 請參閱下面的改編代碼:
* {
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>
uj5u.com熱心網友回復:
使用寬度上的 css calc 函式.two從 90% 寬度中減去 10px(2x5px 邊距),似乎給出了合理的邊距。
width: calc(90% - 10px);
我不確定為什么兩者之間沒有可見的 10 像素(2x5 像素).one邊距.two。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453120.html
上一篇:如何設定沒有ID或Class的div樣式,這也在動態變化的IDdiv內(JS模態彈出視窗)
下一篇:獲取表格標題和正文以匹配列寬
