1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 【css】父div宽度固定 子div横向排列 排不下自动换行

【css】父div宽度固定 子div横向排列 排不下自动换行

时间:2019-07-29 17:11:22

相关推荐

【css】父div宽度固定 子div横向排列 排不下自动换行

前提:

如图,有n个虚线div,未设定样式时每个div独占一行,且宽度均为100%。

现有一需求,要求每个虚线div宽度为文字宽度,并横向排列,排不下时自动换行。

<style>.area {width: 800px;padding: 45px 30px;margin-bottom: 30px;outline: 6px solid #000;}.area div[class*="text"] {outline: 2px dashed #395792;}.area div[class*="text"]:hover {background-color: #ebeef5;}.area span {word-break: break-word;}.area p {margin: 0;}.area .container {background-color: #c0c0c0;padding: 10px;}</style><div class="area"><div class="container"><div class="text1"><span>text1</span></div><div class="text2"><span>text2text2text2text2text2text2text2text2text2text2text2text2text2text2<p>&nbsp;</p></span></div><div class="text3"><span>text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3text3</span></div></div></div>

解决方法:

方法1:子 div 设定 float: left;

方法2:父 div 设定 display: flex;(无需指定子 div 的样式)

推荐方法2,因为方法1需要解决高度不一致的问题,解决这个问题还是要用到方法2,所以不如直接用方法2去实现。

解析:

方法1,子 div 设定 float: left;

如图,text2有2行文字,出现了高度不一致的问题,可以通过设定flex-wrap属性解决。

.container {overflow: hidden;/* 解决设定float无法撑开父div的问题 *//* 解决每个div高度不一致的问题display: flex;flex-wrap: wrap;*/}.container > div {float: left;}

方法2:父 div 设定 display: flex;

.container {display: flex;flex-wrap: wrap;/* 还可以设定div的居中方式justify-content: center;*/}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。