Jon*_*set 59 html css css-selectors
有没有办法隐藏元素的内容,但保持其:before内容可见?说我有以下代码:
HTML:
<span class="addbefore hidetext">You are here</span>
Run Code Online (Sandbox Code Playgroud)
CSS:
.addbefore:before {
content: "Show this";
}
.hidetext {
// What do I do here to hide the content without hiding the :before content?
}
Run Code Online (Sandbox Code Playgroud)
我试过了:
display: none和设置display: inline上:before,但两者都还隐藏 width: 0; overflow: hidden;,但是似乎添加了额外的空间(?) text-indent: -....px,但是
关于我如何做到这一点的任何其他想法?
anr*_*sti 93
您可以使用visibility: hidden,但使用此解决方案,隐藏的内容仍将占用空间.如果这对您无关紧要,您可以这样做:
span {
visibility: hidden;
}
span:before {
visibility: visible;
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是设置font-size跨度为零*到一个非常小的价值.此方法的优点:隐藏的内容不会占用任何空间.缺点:您将无法使用em或%等相对单位作为:before内容的字体大小.
span:before {
content: "Lorem ";
font-size: 16px;
font-size: 1rem; /* Maintain relative font-size in browsers that support it */
letter-spacing: normal;
color: #000;
}
span {
font-size: 1px;
letter-spacing: -1px;
color: transparent;
}
Run Code Online (Sandbox Code Playgroud)
更新(2015年5月4日):使用CSS3,您现在可以使用rem(根EM)单元来维护:before元素中的相对字体大小.(浏览器支持.)
*此帖子的先前版本建议将字体大小设置为零.但是,这在某些浏览器中无法正常工作,因为当font-size设置为零时,CSS不会定义预期的行为.对于跨浏览器兼容性,请使用如上所述的小字体大小.
For better browser support:
Wrap the text that should be hidden within an additional span element, and apply classes to that span to hide the text you wish to be hidden.
HTML:
<span class="addbefore">
<span class="visuallyhidden>This text will not show.</span>
</span>
Run Code Online (Sandbox Code Playgroud)
CSS:
.addbefore:before {
content: "Show this";
}
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
Run Code Online (Sandbox Code Playgroud)
The .visuallyhidden class used above is from the current version of HTML5 Boilerplate: https://github.com/h5bp/html5-boilerplate/blob/master/css/main.css
The advantages of this solution:
font-size solutions.在这里看到它:http://jsfiddle.net/tinystride/A9SSb/