如何给div设置margin/padding时不移动页面其他元素
我想要将头部的内容文本居中,同时不移动头部图片及其他剩余元素。在下方图片中你可以看到我的.portada-texto和.portada-botones位于顶部,被导航栏遮挡。我在绘图工具中用白色方框标注了这两个div元素期望的放置位置。我尝试给父div(#portada)或两个子div(.portada-texto和.portada-botones)设置padding和/或margin来移动它们,但会导致图片位移或是页面底部被撑开,我仅想移动这两个div,不改动其余元素的位置。

我的HTML代码如下:
<section class="portada" id="portada"> <div class="portada-texto"> <h1>Hola, soy Diego Donoso</h1> <h2>Técnico Analista Programador</h2> </div> <div class="portada-botones"> <button>Leer más</button> <button>Contáctame</button> </div> </section>
我的CSS代码如下:
#portada{ min-height: 100vh; /*占满当前屏幕的整个视口高度*/ background-image: url(../images/banner1.webp); /*背景图*/ background-size: cover; /*背景图拉伸铺满容器*/ background-color: rgb(30, 30, 30); /*背景底色*/ background-blend-mode: soft-light; /*背景混合模式,调整封面色调*/ text-align: center; } #portada .portada-texto { display: flex; justify-content: center; flex-direction: column; } #portada .portada-texto h1,h2{ color: white; font-size: 2em; } #portada .portada-botones button{ color: white; background: #ff9800; width: auto; height: auto; font-size: 1.625em; /*26px*/ }
解决方法
方案1:修改父容器布局(推荐)
你遇到padding/margin撑高页面、背景位移的问题,是因为默认容器的盒模型为content-box,新增内边距会叠加到容器总高度上。给父容器加上box-sizing: border-box后配合flex布局调整子元素位置即可,完全不会影响背景和其他元素:
#portada{ min-height: 100vh; background-image: url(../images/banner1.webp); background-size: cover; background-color: rgb(30, 30, 30); background-blend-mode: soft-light; text-align: center; /* 新增以下代码 */ box-sizing: border-box; display: flex; flex-direction: column; align-items: center; /* 要让内容完全垂直居中就加这行 */ justify-content: center; /* 如果只是要避开顶部导航、不需要完全居中,就把上面的justify-content换成下面两行,数值根据导航实际高度调整 */ /* justify-content: flex-start; padding-top: 90px; */ }
方案2:仅偏移目标子元素
如果不想改动父容器的原有布局,直接给两个子元素加位移属性即可,不会触发任何其他元素的位置变化:
#portada .portada-texto { display: flex; justify-content: center; flex-direction: column; /* 新增,数值根据你需要下移的距离调整 */ transform: translateY(90px); } #portada .portada-botones { /* 新增,和上面的数值保持一致 */ transform: translateY(90px); }
内容的提问来源于stack exchange,提问作者Diego Donoso
相关产品推荐
相关产品推荐

