三个div并排,中间有间距

Jas*_*ale 1 html css html5 css3 css-float

我试图将三个div并排放在div中间的间距.

这是我需要的形象: 在此输入图像描述

这是我目前的代码:

<style>
  .box {
    float: left;
    width: 33%;
    background-color: red;
    text-align: center;
    color: #fff;
  }
</style>

<div class="box">Div 1</div>
<div class="box">Div 2</div>
<div class="box">Div 3</div>
Run Code Online (Sandbox Code Playgroud)

我当前代码的问题是它在div 1和2以及div 2和3的中间没有我需要的间距.

DKy*_*leo 5

您可能更好地使用flexbox来实现您的需求.为三个.box div创建一个容器,并使用以下内容对其进行样式设置:

display:flex;
justify-content:space-between;
Run Code Online (Sandbox Code Playgroud)

请记住,您的.box div的宽度需要降低才能达到您想要的空间,并且您不需要浮动:left; 在css.

有关flexboxes的更多信息,请单击此处:https://css-tricks.com/snippets/css/a-guide-to-flexbox/


Tem*_*fif 5

一个简单的CSS 网格解决方案怎么样:

.container {
  display: grid;
  grid-gap: 10px;  /* Simply adjust this value !*/
  grid-template-columns: repeat(3, 1fr); /* OR grid-template-columns: 1fr 1fr 1fr;*/
  grid-auto-rows: 1fr;
  border:1px solid green 
}

.container>div {
  border: 1px solid red;
  height: 20px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)