给定一个导航栏样式容器,其中包含按钮列表。这些按钮包含一个 svg 图像以及一些文本。按钮的数量可能会在运行时发生变化,文本也可能由于 i18n 而改变。这几乎消除了仅通过媒体查询解决此问题的可能性。
大屏幕:
------------------------------------------
| -------------------- --------------- |
||svg create new page | | svg edit page | |
| -------------------- --------------- |
------------------------------------------
当屏幕变小时,应使用替代的较短文本:
屏幕较小:
-------------------------------
| ----------- ---------- |
||svg create | | svg edit| |
| ----------- ---------- |
-------------------------------
最后,当我们甚至无法使其适合时,仅显示 SVG 图标而不显示文本:
-------------------
| ----- ----- |
|| svg | | svg | |
| ----- ----- |
-------------------
我以前使用媒体查询来完成这项工作,但随着按钮在运行时可能更改的越多,这变得越来越复杂和困难。有没有更好的方法CSS支持这样的东西?
.buttons {
whitespace: nowrap;
}
<div class="buttons">
<button>
<span>svg</span>
<span class="long">
create new page
</span>
<span class="short">
create
</span>
</button>
<button>
<span>svg</span>
<span class="long">
edit page
</span>
<span class="short">
edit
</span>
</button>
</div>
链接到小提琴
我有两种可能的解决方案:
-
使用 css 定位特定的屏幕尺寸,例如:
@media(最小宽度:1440 像素(和(最大宽度:1600 像素({/* * 样式去这里 */}
-
如果你使用的是 angular,请尝试使用 ng-class;它将帮助您使用条件类,这样您就可以放置类似的东西
...
另外,请尝试使用
.yourClass{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
所以它不会溢出。 我希望这有帮助
我知道它不完全是你问的,但以下怎么样:
.buttons {
display: flex;
flex-flow: row nowrap;
}
button {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
小提琴:https://jsfiddle.net/cnh3z5jL/
它隐藏从右侧开始的上下文,使窗口变小。这对你有用吗?
编辑:您可以跳过
text-overflow: ellipsis;
如果这对你来说看起来更好
使用代替按钮并像按钮一样为其添加样式
<a href="" class="test button"></a>
@media (min-width: 1440px) and (max-width: 1600px) {
.test:before {
content:"hi large text";
display:block;
}
}
@media (min-width: 800px) and (max-width: 1200px) {
.test:before {
content:"hi medium text";
display:block;
}
}
@media only screen and (max-width: 767px) {
.test:before {
content:"hi small text";
display:block;
}
}
此问题的解决方案称为容器查询。浏览器尚不支持,但有几种方法可以使用javascript使其工作。
还有一些库可用于处理繁重的工作 - 但这通常取决于所使用的框架。