设置div padding导致flex右侧子项尺寸变大如何解决
问题背景
我是HTML和CSS初学者,制作了一款沿中线50/50等分的生日贺卡。在左侧区域插入图片后,发现右侧区域的文本距离中线过近,因此给右侧区域设置padding-left: 50px;把文本向右推,但操作后右侧盒子尺寸被撑大。需求是右侧盒子保持原有固定尺寸,仅调整盒内文本位置,不触发容器尺寸变化。
现有代码
CSS部分
.card { box-sizing: border-box; width: 600px; height: 400px; border: 5px solid; display: flex; } .left { flex: 1; background-image: url("https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/golden-retriever-royalty-free-image-506756303-1560962726.jpg"); border-style: solid; background-size: cover; background-position: 60% 5%; width: auto; height: auto; max-width: 300px; max-height: 600px; } .right { flex: 1; background-color: burlywood; border: 5px solid; padding-left: 50px; }
HTML部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Flex</title> </head> <body> <div class="card"> <div class="left"></div> <div class="right"> <h1 class="title">Hello</h1> <h2 class="birthday">Happy Birthday</h2> <p class="message">We really miss you and are thinking about you</p> <p class="bye"> Lots of love and see you soon x</p> </div> </div> </body> </html>
问题原因
CSS默认使用content-box盒模型:元素设置的width属性只包含内容区宽度,padding、border的宽度都会额外叠加到元素总宽度上。
你只给外层.card容器设置了box-sizing: border-box(这种盒模型下padding、border会算入设定宽度内,不会撑大盒子),但子元素.right仍然继承默认的content-box规则,所以加padding-left后,总宽度=flex分配的宽度+50px内边距+左右边框宽度,自然就超出原有尺寸把盒子撑大了。
解决方法
两种方法都能实现需求,按需选择即可:
- 方法1:给右侧容器加
box-sizing: border-box
直接给.right加上盒模型属性,内边距就会被算入flex分配的固定宽度里,不会撑大容器,原来写的padding-left不需要改动:
想一劳永逸避免后续再出现同类撑大盒子的问题,可以全局设置盒模型继承:.right { flex: 1; background-color: burlywood; border: 5px solid; padding-left: 50px; box-sizing: border-box; /* 新增这行 */ }*, *::before, *::after { box-sizing: inherit; } body { box-sizing: border-box; } - 方法2:直接偏移内部文本,不调整容器内边距
如果不想改盒模型,直接删掉.right上的padding-left,给内部所有文本元素加左外边距,完全不会影响外层容器的尺寸:.right { flex: 1; background-color: burlywood; border: 5px solid; /* 删掉padding-left: 50px; */ } /* 给右侧所有文本子元素加左偏移 */ .right > * { margin-left: 50px; }
内容的提问来源于stack exchange,提问作者Taz I
相关产品推荐
相关产品推荐

