我尝试过的事情:
<div class="my-container">
<div class="left"></div>
<div class="middle"></div>
<div class="right"> </div>
</div>
.my-container{
display: inline;
width: 400px;
height: 50px;
background-color: green;
}
.left{
display: inline-block;
width: 50px;
height: 50px;
background-color: red;
}
.middle{
display: inline-block;
width: 300px;
height: 50px;
background-color: blue;
}
.right{
display: inline-block;
width: 50px;
height: 50px;
background-color: yellow;
}
结果是元素之间有一些空间,并且容器的大小不完全等于其子树的总和。我想让三个孩子与我的容器完全匹配。
答案 0 :(得分:1)
在display: flex;
上使用my-container
并从子元素中删除inline-block
.my-container {
display: flex;
width: 400px;
height: 50px;
background-color: green;
}
.left {
width: 50px;
height: 50px;
background-color: red;
}
.middle {
width: 300px;
height: 50px;
background-color: blue;
}
.right {
width: 50px;
height: 50px;
background-color: yellow;
}
<div class="my-container">
<div class="left"></div>
<div class="middle"></div>
<div class="right"> </div>
</div>
OR
在font-size: 0;
元素上添加my-container
。如果其中包含文本,则在其中的div上添加字体大小。
.my-container {
display: inline;
width: 400px;
height: 50px;
background-color: green;
font-size: 0;
}
.my-container div {
font-size: 16px;
}
.left {
display: inline-block;
width: 50px;
height: 50px;
background-color: red;
}
.middle {
display: inline-block;
width: 300px;
height: 50px;
background-color: blue;
}
.right {
display: inline-block;
width: 50px;
height: 50px;
background-color: yellow;
}
<div class="my-container">
<div class="left"></div>
<div class="middle"></div>
<div class="right"> </div>
</div>
答案 1 :(得分:0)
如果可以的话,我建议您使用Nandita's answer,但是如果由于某种原因而不能使用flexbox布局(例如browser support):
空格是由HTML文件中的空格引起的,可以通过两种方法解决。
.my-container {
display: inline;
width: 400px;
height: 50px;
background-color: green;
}
.left {
display: inline-block;
width: 50px;
height: 50px;
background-color: red;
}
.middle {
display: inline-block;
width: 300px;
height: 50px;
background-color: blue;
}
.right {
display: inline-block;
width: 50px;
height: 50px;
background-color: yellow;
}
<div class="my-container">
<div class="left"></div><!-- These comments "remove" the whitespace without breaking your code formatting too badly
--><div class="middle"></div><!--
--><div class="right"></div>
</div>
font-size
设置为0
.my-container {
display: inline;
width: 400px;
height: 50px;
background-color: green;
font-size: 0; /* Make the whitespace take up no actual space */
}
.left {
display: inline-block;
width: 50px;
height: 50px;
background-color: red;
font-size: 16px; /* Make sure to set the font back to normal on the children */
}
.middle {
display: inline-block;
width: 300px;
height: 50px;
background-color: blue;
font-size: 16px;
}
.right {
display: inline-block;
width: 50px;
height: 50px;
background-color: yellow;
font-size: 16px;
}
<div class="my-container">
<div class="left"></div>
<div class="middle"></div>
<div class="right"> </div>
</div>