如何调整Flex右侧列宽,保持容器居中且Google Maps尺寸不变
问题描述
使用Flexbox布局的两列内容,设置容器width:50%后,容器不再水平居中,且Google Maps的尺寸会随容器宽度变化。需求是:缩小容器整体尺寸的同时,保持Flex容器在页面居中,且Google Maps的宽高维持固定值。
修改后的CSS代码
#google-maps { background: #FFFFFF; width: 600px; height: 500px; flex-shrink: 0; /* 强制禁止地图被Flex容器压缩 */ } .hours-and-location { flex: 1; /* 让右侧列自动填充容器剩余空间 */ max-width: 400px; /* 限制右侧列最大宽度,可按需调整 */ } #hours-and-location-container { display: flex; flex-direction: row; justify-content: center; gap: 2em; /* 用gap统一控制两列间距,替代margin更简洁 */ margin: 3em auto; /* auto实现容器水平居中,上下保留3em边距 */ width: 80%; /* 容器整体宽度,可按需修改 */ max-width: 1200px; /* 限制容器最大宽度,避免大屏幕下布局过宽 */ } .column { display: flex; flex-direction: column; margin: 0; /* 移除多余margin,避免与容器gap冲突 */ } .locations { width: 100%; } .page-title-header { text-align: center; }
修改后的HTML代码
<h1 class="page-title-header"> Hours and Locations </h1> <div id="hours-and-location-container"> <iframe id="google-maps" src="https://www.google.com/maps/d/u/0/embed?mid=1_iD-tpjnLUFwGIWoEcsx05qBgbx112w&ehbc=2E312F"> </iframe> <div class="hours-and-location"> <div class="locations column"> <h2> Locations </h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> <p> Augue mauris augue neque gravida in. Est sit amet facilisis magna. In vitae turpis massa sed elementum tempus egestas sed. </p> <p> Lectus quam id leo in vitae turpis massa sed. </p> <p> Imperdiet proin fermentum leo vel orci porta non pulvinar. A iaculis at erat pellentesque adipiscing commodo elit at imperdiet. Semper eget duis at tellus at urna condimentum. Purus in massa tempor nec feugiat nisl. </p> </div> <div class="hours"> </div> </div> </div>
关键修改说明
- 容器居中逻辑:给
#hours-and-location-container设置margin: 3em auto;,利用auto实现水平居中。原代码仅用justify-content:center只能控制容器内部元素的对齐,无法让容器自身在页面居中。 - 固定地图尺寸:
- 给
#google-maps明确设置固定宽高,替代iframe标签内的属性,样式统一可控。 - 添加
flex-shrink:0;,强制禁止Flex容器压缩地图宽度,确保容器变窄时地图尺寸不受影响。
- 给
- 右侧列宽度控制:给
.hours-and-location设置flex:1,让它自动填充容器剩余空间;搭配max-width可限制右侧列的最大宽度,避免内容过宽影响阅读体验。 - 间距优化:用容器的
gap属性替代列的margin,更简洁地控制两列之间的间距,避免重复设置margin导致的布局冲突。
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

