如何让三个包含h1的div元素互相远离,避免页面整体位移?
解决三个带H1的Div间距过紧问题
我尝试让页面里三个包含h1元素的div互相远离,不要过于紧凑,但没能成功。给每个div设置width好像没效果,添加margin和padding时,整个页面都会跟着移动,没法单独调整单个div的间距。
我的HTML代码(main部分)
<main> <div class="who"> <h1>Who We Are</h1> </div> <div class="what"> <h1>What We Do</h1> </div> <div class="where"> <h1>Where We Work</h1> </div> </main>
我的CSS代码
*{ padding:0; margin: 0; box-sizing: border-box; } body{ font-family: 'Calibri'; color: #222; padding-bottom: 50px; } header{ height:100px; display:flex; justify-content: space-around; align-items: center; } ul{ display:flex; list-style-type:none; align-items: center; justify-content: center; } ul li a{ color: rgb(0,0,0); text-decoration: none; padding:7px 15px; transition: all 0.3s ease-in-out; font-size: 17px; font-weight: 600; letter-spacing: 1px; text-transform: uppercase; display:inline-block; } li a::after{ content:''; display:block; height:4px; width:0; background: #FCAE1E; } li a:hover::after{ width:100%; } main{ display: flex; height:calc(100vh - 100px); align-items: center; justify-content: center; } .who{ width: 30%; } .what{ width: 30%; } .where{ width: 30%; }
问题原因
你给每个div设了30%宽度,三个加起来占90%,但main的justify-content: center会把剩下的10%空间全部分配在容器左右两侧,div之间没有额外间距,所以看起来还是紧凑。另外直接给div加margin会让子元素总宽度超过容器,flex容器默认不换行,就会导致整个页面偏移。
解决方案
方法1:用Flex的gap属性(推荐)
直接给main加gap属性,专门控制flex子元素的间距,不会影响容器位置:
main{ display: flex; height:calc(100vh - 100px); align-items: center; justify-content: center; gap: 40px; /* 按需调整间距大小 */ }
方法2:给div设置左右margin
给每个div加左右margin,同时给main加换行属性防止溢出:
.who, .what, .where{ width: 30%; margin: 0 20px; /* 左右各20px间距 */ } main{ display: flex; height:calc(100vh - 100px); align-items: center; justify-content: center; flex-wrap: wrap; /* 避免子元素总宽度超容器时溢出 */ }
方法3:调整justify-content为分散对齐
如果想让div在main里均匀分布,修改justify-content并确保main占满宽度:
main{ display: flex; height:calc(100vh - 100px); align-items: center; justify-content: space-around; /* 子元素左右间距相等 */ /* 也可以用justify-content: space-between; 两端对齐,中间间距相等 */ width: 100%; /* 确保main占满页面宽度 */ }
内容的提问来源于stack exchange,提问作者2k adc
相关产品推荐
相关产品推荐

