CSS 隐藏文本,留下图标元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33999836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide text, leave icon elements
提问by Digital Ninja
I have a pretty big site now, and it would be time-consuming to change the codes of all of the buttons, so I am wondering if CSS could do something for me with no HTML code change.
我现在有一个相当大的网站,更改所有按钮的代码会很耗时,所以我想知道 CSS 是否可以在不更改 HTML 代码的情况下为我做一些事情。
Every page has an action bar with some buttons, which all consist of an icon and text. Something like this:
每个页面都有一个带有一些按钮的操作栏,这些按钮都由一个图标和文本组成。像这样的东西:
<div class="action-bar">
<a href="" class="btn btn-primary">
<i class="fa fa-icon"></i>
Button label
</a>
<a href="" class="btn btn-primary">
<i class="fa fa-icon"></i>
Button label
</a>
</div>
What I want to achieve now, is that on the mobile devices, the text inside the button will not display; only the icon should display.
我现在想要实现的是,在移动设备上,按钮内的文字不会显示;只应显示图标。
If I had a markup like this one:
如果我有这样的标记:
<a href="" class="btn btn-primary">
<i class="fa fa-icon"></i>
<span class="label">Button label</label>
</a>
Then I know I could hide all the labels by doing:
然后我知道我可以通过执行以下操作来隐藏所有标签:
@media(max-width:768px) {
.btn .label {
display: none;
}
}
So what I'm wondering is, is there a pure CSS equivalent to this, but with the first HTML markup where there is no span.label
?
所以我想知道的是,是否有一个与此等效的纯 CSS,但是第一个 HTML 标记没有span.label
?
回答by Rokin
You can set the font size to zero:
您可以将字体大小设置为零:
.btn { font-size: 0; }
If your icons contain text, overwrite their font size:
如果您的图标包含文本,请覆盖其字体大小:
.fa { font-size: initial; }
回答by Szabolcs Páll
You can use:
您可以使用:
@media(max-width:768px) {
.btn {
color: transparent;
}
.btn > .fa{
color: black; //or color of your choice
}
}
This will hide the text, but it doesn't deal with the size of the button.
这将隐藏文本,但不会处理按钮的大小。
If you know the size of the icons, you can force that size to the .btn
s and then use position:absolute;top:0;left:0;z-index:1;
on your icons.
如果您知道图标的大小,则可以将该大小强制为.btn
s,然后position:absolute;top:0;left:0;z-index:1;
在您的图标上使用。
回答by Mr Lister
Assuming the width of the icons is 1em, you can do something like
假设图标的宽度是 1em,你可以做类似的事情
/* just to make the icon visible */
.fa.fa-icon {
display:inline-block;
width:1em; height:1em;
background:orange;
}
a {
display:inline-block;
width: 1em; /* set to same as icon */
color:white; /* set to same as background */
overflow:hidden;
}
<div class="action-bar">
<a href="" class="btn btn-primary">
<i class="fa fa-icon"></i>
Button label
</a>
<a href="" class="btn btn-primary">
<i class="fa fa-icon"></i>
Button label
</a>
</div>
(where the orange squares are the icons; I didn't feel like including the complete FontAwesome, so I had to fake it a little.)
(橙色方块是图标;我不想包含完整的 FontAwesome,所以我不得不假装一下。)