gpt4 book ai didi

html - 为什么向我的 div 添加边距会将其内容(列)推离页面?

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:14 25 4
gpt4 key购买 nike

向 div 添加边距会将右侧的列推到屏幕的右侧。

我试过为 和 都添加边距,改变宽度,甚至完全从 CSS 中删除宽度属性。

完全没有边距,3 列完全适合屏幕宽度,默认的小边距显示我页面的背景颜色。添加任何边距都会把整个事情搞砸。

<HTML>
<main>
<section>
Some text 1
</section>

<section>
Some text 2
</section>

<section>
Some text 3
</section>
</main>


CSS

<<<<<<<SOME MEDIA QUERIES TO MAKE IT ADAPTABLE FOR MOBILE>>>>>>>

@media (min-width: 620px) {
main {
column-count: 2;
}
section {
break-inside: avoid;
}
}

@media (min-width: 960px) {
main {
column-count: 3;
}
}


<<<<<<<<<<<<NORMAL CSS>>>>>>>>>>>>>>

main {
width: 100%;
margin-right: 5%; <<<<<PROBLEM AREA
margin-left: 5%;
}

section {
height: 25%;
margin-bottom: 5%;
padding: 20px;
display: inline-block;
}

我希望 div 的左右各有 5% 的边距,div 之间没有边距。

最佳答案

CSS 边距被添加到元素的外部。如果你有 <div>宽度为 100% 并在两侧添加 5% 的边距,该元素现在为 110% 宽。

如果你想添加边距,你必须在元素的宽度中考虑它们。如果宽度和边距都是百分比,你可以减去边距:

main {
width: 90%;
margin-left: 5%;
margin-right: 5%;
}

如果宽度和边距使用不同的单位(例如宽度:100%,边距:24px),您可以使用 css calc :

main {
width: calc(100% - 48px);
margin-left: 24px;
margin-right: 24px;
}

在下面的代码片段中,第一行和第二行之间的唯一区别是边距。请注意,盒子本身的大小相同。在框外添加边距。

* {
box-sizing: border-box;
padding: 0;
margin: 0;
}

.grid {
background-color: white;
background-image: linear-gradient(transparent 24px, #999 25px), linear-gradient(90deg, transparent 24px, #999 25px);
background-size: 25px 25px, 25px 25px;
background-position: 1px 1px;
height: 100vh;
}

.container > div {
display: inline-block;
width: 100px;
background: bisque;
margin: 0 21px 22px 0;
min-height: 50px;
}

.container.second > div {
background: tomato;
margin: 0 46px 15px 0;
}
<div class="grid">
<div class="container first">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

<div class="container second">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>

关于html - 为什么向我的 div 添加边距会将其内容(列)推离页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56333467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com