我知道这很容易使用Javascript但是...有什么办法只用CSS吗?
假设我们在父母(米色)中有两个元素(绿色和红色).红色元素应始终位于绿色元素的右侧,除非绿色元素(因为内容)太大而不适合父母,在这种情况下红色元素将超过绿色元素(正常行为将是红色元素停留在绿色元素的右侧,因此由于父母的溢出而被隐藏)
换句话说:red.x = min(green.x + green.w,beige.x + beige.w-red.w)

有关更多信息,请参阅具体的HTML:
<div class="beige" style="width:250px"> <!-- parent with a given width (unknown until the page is rendered) & overflow hidden -->
<a class="green"> <!-- link with display:inline -->
content
<em class="red"></em> <!-- actually a button, 15 px width -->
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
编辑: @kyledws答案很棒,但我会用更多信息(需要的东西)更新问题,例如:
如果你能够将内容包装<a>在一个span然后尝试这个.
HTML
<div class="beige">
<a class="green" href="#">
<span class="content">This is some text.</span><em class="red"></em>
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.beige {
background-color: #EBDFA0;
height: 32px;
overflow: hidden;
border: 4px solid #EBDFA0;
white-space: nowrap;
width: 400px;
}
.green {
background-color: #4CA73D;
color: #222;
display: inline-block;
height: 100%;
text-decoration: underline;
vertical-align: middle;
}
.content {
display: inline-block;
height: 100%;
margin-left: 4px;
position: relative;
width: 100%;
max-width: 364px;
top: -50%;
}
.red {
border: 2px solid red;
display: inline-block;
height: 28px;
position: absolute;
width: 28px;
}
Run Code Online (Sandbox Code Playgroud)
本质上<a class="green">,<span class="content">并且<em class="red">必须display: inline-block与<span class="content">必须width: 100%与max-width之间的不同<div class="beige">和<em class="red"减去任何额外的填充/保证金/边框等.(所以在这个例子中,max-width: 364px)通过对设定的宽度span会强制em外面的这容器,但通过设置max-width你停止em从主包装外流动.
这是一个示例的codepen.io链接.
(注意:上面的大多数CSS只是为了使示例看起来像你的图像.)
更新:
显示或隐藏<em class="red">添加:hover伪类.beige和可见性或不透明度.red.(如果要使用转换,请使用不透明度.)
.red {
opacity: 0;
}
.beige:hover .red {
opacity: 1;
}
Run Code Online (Sandbox Code Playgroud)由于宽度<div class="beige">是未知的,你不能使用CSS来设置max-width的<span class="content">.
(100%的max-width: calc(100% - 28px)宽度<a class="green">不是<div class="beige">.我不能用伪元素,定位,浮动或不同的显示类型(如flex)来破解它.)
解决这个问题的方式是固定max-width的<span class="content">在CSS(如以上示出)或使用Javascript来检测的宽度<div class="beige">,然后设置max-width.
content.style.maxWidth = beige.clientWidth - red.clientWidth + "px";
Run Code Online (Sandbox Code Playgroud)我用可见性和Javascript版本更新了示例.
另外,我加入position: absolute到.red这样<span class="content">不会对右边空白处.
| 归档时间: |
|
| 查看次数: |
1325 次 |
| 最近记录: |