css flexbox元素表现为行内联元素(子元素溢出父元素)

0lvr5msh  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(151)

css属性display设置为flex的节(具有class属性top-level-section)的行为与内联元素类似:从填充子元素开始,它会溢出父元素(id为main的div)。
有什么想法为什么会发生这种情况以及如何解决?
https://jsfiddle.net/ruud00000/qd6c3nrb/1/
CSS:

html {
    scroll-behavior: smooth;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
input, textarea, button {
    padding: 10px 17px;
}
html, body, section, footer, div, input, textarea, button {
    font-family: 'DM Sans',sans-serif;
    font-size: large;
}
html, body, section, footer, div {
    border-width: thin;
}
button {
    background-color: chocolate;
    margin: auto;
    display: flex;
    border: none;
    color: white;
}
body {
    display: flex;
    flex-direction: column;
    border-color: rgb(0, 0, 0);
    margin:0px;
    width: 100%;
    align-items: center;
}
section {
    display: flex;
    flex-direction: column;
    border-style: solid;
    border-color: grey;
    margin:1px;
    padding: 20px;
    }
.top-level-section {
    width: 95%;
    /*padding: 20px;*/
    }
@media (max-width: 1280px) {
/* CSS that should be displayed if width is equal to or less than 800px goes here */
    html {
        width: 100%;
    }
}
div {
    border-style: solid;
    border-color: rgba(128, 128, 128, 0.301);
    margin:1px;           
}
footer {
    display: flex;
    flex-direction: column;
    border-style: dashed;
    border-color: grey;
    margin:1px;           
}
h1 {
    font-size: xxx-large;
}
h2 {
    font-size: xx-large;
    color: grey;
}
h3 {
    font-size: x-large;
    color: rgba(128, 128, 128, 0.301);
}
p {
    font-size: large;
}
h1, h2, h3, p, button {
    display: inline-block;            
}
#navbar {
    position: fixed;
    top:0px;
    height: 50px;
    width: 100%;
    background-color: white;
    display: flex;
    border-style: none; 
    margin: 0px; 
    align-items: center;
    justify-content: space-around;
}
#navbar-pages {
    padding:1px;
}
#navbar div {
    margin: 0px;
    border-style:none; 
}
#main {
    margin-top: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

#alleclubs, #ikwilkennismaken, #allelocaties, #meeroverkegelen, #interesse {
    display: none;
}
.close-section-button {
    display: flex;
    margin: auto;
}

HTML:

<body>
    <div id="main">
        <section class = "top-level-section" id="home">
    
            
            <p>[TODO ]</p>
        </section>
    </div>
</body>

我试图隔离这个问题,但当我从头开始创建一个包含一个节的div时,我无法重现它。

b5buobof

b5buobof1#

这是因为您没有将box-sizing设置为border-box。
虽然您已经将部分的宽度设置为95%,但当上述box-sizing未设置为border-box时,20 px的padding将单独计算。添加此属性后,填充将被设置为指定宽度的一部分。
尝试将box-sizing: border-box添加到“.top-level-section”或“.section”类。或者你也可以全局添加它,像这样:

* {
  box-sizing: border-box;
}

相关问题