如何使用css根据内容宽度在div中排列这些tab / bubble元素?

时间:2018-04-03 04:52:09

标签: html css flexbox grid

我正在尝试将一些元素与从后端生成的文本内容放在容器div中。 这是HTML:

<div class="mainContainer">
  <div class="1"> ASDdjiajwio </div>
  <div class="2"> asdasda  </div>
  <div class="3"> asdgrsgse </div>
  <div class="4"> sdf sfsef </div>
  <div class="5"> asdahtd sfsefse </div>
  .
  .
  .
  .
  <div class="n"> and so on.. </div>
</div>

下图显示了我希望如何放置它们。

这就是我想要放置元素的方式:

enter image description here

我可以使用网格,其中css如下:

.mainContainer{
       width: 30em;
       height: 20em;
       display: grid;
       grid-template-columns: 1fr 1fr 1fr;
}

但是它会看起来像这样 -

这就是它的外观

enter image description here

我希望使用css在容器div中正确包装所有元素。有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

如果这是您要找的,只需执行

.mainContainer div{
    display: inline-block;
}

代码说明

内联块

  

将元素显示为内联级块容器。元素本身被格式化为内联元素,但您可以应用高度和宽度值

.mainContainer div{
	display: inline-block;
	border: 2px solid pink;
	border-radius: 25px;
	margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
  <title>Blocks</title>
  <!-- Do not change this file - add your CSS styling 
       rules to the blocks.css file included below -->
  <link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<div class="mainContainer">
  <div class="1"> ASDdjiajwio </div>
  <div class="2"> asdasda  </div>
  <div class="3"> asdgrsgse </div>
  <div class="4"> sdf sfsef </div>
  <div class="5"> asdahtd sfsefse </div>
  <div class="6"> sdf sfsef </div>
  <div class="7"> asdahtd sfsefse </div>
  <div class="4"> sdf sfsef </div>
  <div class="5"> asdahtd sfsefse </div>
  <div class="3"> asdgrsgse </div>
  <div class="4"> sdf sfsef </div>
  <div class="5"> asdahtd sfsefse </div>
  <div class="6"> sdf sfsef </div>
  <div class="7"> asdahtd sfsefse </div>
  <div class="4"> sdf sfsef </div>>
  <div class="4"> sdf sfsef </div>
  <div class="5"> asdahtd sfsefse </div>
  <div class="3"> asdgrsgse </div>
  <div class="4"> sdf sfsef </div>
  <div class="5"> asdahtd sfsefse </div>
  <div class="6"> sdf sfsef </div>
  <div class="7"> asdahtd sfsefse </div>
  <div class="4"> sdf sfsef </div>
  <div class="n"> and so on.. </div>
</div>
</body>
</html>

答案 1 :(得分:1)

我认为这对你有帮助

<div class="mainContainer">
  <div class="one"> ASDdjiajwio </div>
  <div class="one"> asdasda  </div>
  <div class="one"> asdgrsgse </div>
  <div class="one"> sdf sfsef </div>
  <div class="one"> asdahtd sfsefse </div>

  <div class="one"> and so on.. </div>
</div>

在CSS中

.mainContainer{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;

}
.one
{
   border:2px solid #ef75db;
       border-radius:30px;
       text-align:center;
       margin:15px;
       padding:15px;
       color:#ef75db;
       font-size:18px;
}

这是工作小提琴https://jsfiddle.net/86g20h39/8/