移动端实现按钮填满父div宽度的问题求助
问题:移动端按钮无法填满父容器宽度的解决方法
问题描述
当屏幕宽度≤750px时,将.outer元素的flex-direction设为column实现单列布局,但设置.cta-button的width:100%后,按钮无法填满父div的宽度。
原始代码
HTML代码
<div class="outer"> <div class="text-caption"> <b>Title Text</b> <div class="or-get-started"> Caption text </div> </div> <div class="button-right"> <a href="https://www.google.com" rel="noopener"> <button class="cta-button">Lorem ipsum dolor →</button></a> </div> </div>
CSS代码
@media (max-width: 750px) { .outer { flex-direction: column; } .cta-button { width:100%; } }
解决方法
问题出在嵌套结构的宽度继承逻辑上:
.outer改为column布局后,子元素默认宽度为内容宽度,.button-right没有自动撑满父容器;- 按钮的直接父元素
<a>是行内元素,宽度由内容决定,按钮设置width:100%只会相对于这个行内<a>的宽度,无法撑满外层容器。
修改后的CSS媒体查询代码:
@media (max-width: 750px) { .outer { flex-direction: column; } /* 让.button-right撑满父容器宽度 */ .button-right { width: 100%; } /* 将<a>转为块级元素,撑满.button-right */ .button-right a { display: block; width: 100%; } /* 按钮撑满父元素<a>的宽度 */ .cta-button { width: 100%; } }
也可以用flex布局特性简化写法:
@media (max-width: 750px) { .outer { flex-direction: column; } .button-right { flex: 1; /* 让.button-right在column布局下自动撑满可用宽度 */ } .button-right a { display: flex; /* 用flex布局让按钮自动适配父元素宽度 */ } .cta-button { flex: 1; /* 按钮自动撑满父元素<a> */ } }
内容的提问来源于stack exchange,提问作者ggg
相关产品推荐
相关产品推荐

