html - 按钮背景使用 :before not showing unless content property has a value

标签 html css

<分区>

我有一个奇怪的问题...我有一个按钮,没什么特别的,就是这样一个按钮

<button class="btn btn--error">
    Button Text
</button> 

现在我希望除了我的按钮文本之外还有一个图像,我希望使用 CSS 来完成此操作而不是在按钮中使用 img 标签。所以我使用了 :before 伪元素,这是我的 CSS(注意它是 SCSS)

.btn {
  font-family: 'Roboto', sans-serif;
  text-align: center;
  text-transform: capitalize;
  text-decoration: none;
  outline: 0;
  margin-bottom: 2px;
  padding: 0 0 0 0;

  &:before {
    background: url("/assets/images/icons/svg/ic_add_24px.svg") no-repeat top left;
    background-size: contain;
    content: '';
    width: 18px;
    height: 18px;
  }
 }

图像的位置是正确的,但是在浏览器中我看不到背景图像...

enter image description here

然而,当我将 content 属性添加到 :before 伪元素时,就像这样

&:before {
    background: url("/assets/images/icons/svg/ic_add_24px.svg") no-repeat top left;
    background-size: contain;
    content: '___';
    width: 18px;
    height: 18px;
  }

我现在可以看到背景图片了!

enter image description here

我怎样才能看到背景图像而不必在内容属性中放置文本?感谢您提供任何帮助和建议。

最佳答案

https://jsfiddle.net/4n1e8ksw/4/

将行内 block 添加到伪元素。伪元素默认是内联的,如果没有内容,它们的宽度和高度为 0。

.btn {
  font-family: 'Roboto', sans-serif;
  text-align: center;
  text-transform: capitalize;
  text-decoration: none;
  outline: 0;
  margin-bottom: 2px;
  padding: 30px;

  &:before {
    background: url("https://cdn4.iconfinder.com/data/icons/new-google-logo-2015/400/new-google-favicon-512.png") no-repeat top left;
    background-size: contain;
    content: '';
    width: 18px;
    height: 18px;
    display: inline-block;
  }
 }

关于html - 按钮背景使用 :before not showing unless content property has a value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554927/

上一篇:javascript - 加载本地 css 和 js 文件时出现 Cors 错误

下一篇:css - 修复 react-select 下拉列表的高度(React Material UI)

相关文章:

python - 将 HTML 中的 Python 代码与传入的变量组合在一起

php - 嵌入式PHP,停不下来?

html - HTML 表单的跨浏览器兼容性问题

html - 试图让横幅漂浮在盒子上并卡在上面

jquery - Box2djs,JS 物理引擎 - 为球对象设置背景图像?

javascript - 自定义文本布局 CSS-JS

html - 背景颜色仅适用于第一个单元格

html - CSS 拉伸(stretch)到 100% 高度

javascript - 在多行 div 中隐藏部分溢出的文本?

html - Style Font Awesome 列出所有其他元素符号颜色