我有两行:第一行有5个按钮,第二行有一个div,应该和按钮一样长。
这是我的代码:
BODY * {
box-sizing: border-box;
}
.container {
background: blue;
width: 100%;
height: 66px;
position: relative;
}
.logo {
background: red;
width: 65px;
height: 65px;
}
.rightcontainer {
position: absolute;
right: 0;
top: 0;
background-color: green;
}
.buttons > DIV {
display: inline-block;
padding: 5px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.buttons > DIV:first-child {
max-width: 30%;
}
.search {
width: 100%;
background-color: yellow;
}
OKAY:
<div class="container">
<div class="logo"></div>
<div class="rightcontainer">
<div class="buttons">
<div>Buttons 1</div>
<div>Buttons 2</div>
<div>Buttons 3</div>
<div>Buttons 4</div>
</div>
<div class="search">
Search
</div>
</div>
</div>
Not okay: The gap between button 4 and border should be gone
<div class="container">
<div class="logo"></div>
<div class="rightcontainer">
<div class="buttons">
<div>Buttons 1 long long long long</div>
<div>Buttons 2</div>
<div>Buttons 3</div>
<div>Buttons 4</div>
</div>
<div class="search">
Search
</div>
</div>
</div>
看到这个小提琴:https://jsfiddle.net/7a50j4oa/1/
第一个按钮应该有max-width
,具体取决于百分比。
如果按钮较大(使用max-width
),则第二行宽度不会减小。
这种风格是问题(如果我使用px值,一切正常)
.buttons > DIV:first-child
{
max-width:30%;
}
我是如何实现这一目标的? flexbox会帮忙吗?
提前致谢。
答案 0 :(得分:4)
将此添加到您的代码中:
.rightcontainer {
width: 45%; /* or another percentage that works for you */
}
代码中的max-width: 30%
无效,因为您没有为包含块定义宽度。
以下是包含块的代码:
.rightcontainer {
position: absolute;
right: 0;
top: 0;
background-color: green;
}
以下是按钮后代的代码:
.buttons > DIV:first-child { max-width: 30%; }
这是规范所说的:
10.4 Minimum and maximum widths:
min-width
andmax-width
这两个属性允许作者将内容宽度约束为a 一定的范围。
百分比值
指定用于确定已使用值的百分比。百分比 是根据生成的框的宽度计算的 包含块。
这就是为什么您的max-width
使用像素而不是百分比值。
BODY * {
box-sizing: border-box;
}
.container {
background: blue;
width: 100%;
height: 66px;
position: relative;
}
.logo {
background: red;
width: 65px;
height: 65px;
}
.rightcontainer {
position: absolute;
right: 0;
top: 0;
background-color: green;
width: 45%; /* NEW */
}
.buttons > DIV {
display: inline-block;
padding: 5px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.buttons > DIV:first-child {
max-width: 30%;
}
.search {
width: 100%;
background-color: yellow;
}
<div class="container">
<div class="logo"></div>
<div class="rightcontainer">
<div class="buttons">
<div>Buttons 1</div>
<div>Buttons 2</div>
<div>Buttons 3</div>
<div>Buttons 4</div>
</div>
<div class="search">Search</div>
</div>
</div>
Not okay: The gap between button 4 and border should be gone
<div class="container">
<div class="logo"></div>
<div class="rightcontainer">
<div class="buttons">
<div>Buttons 1 long long long long</div>
<div>Buttons 2</div>
<div>Buttons 3</div>
<div>Buttons 4</div>
</div>
<div class="search">Search</div>
</div>
</div>