70

Here is a fiddle.

<p>foo <a class="infolink" href="#">bar</a> baz</p>

and

a.infolink::before
{
    content: '?';
    background: blue;
    color: white;
    width: 20ex;
    height: 20ex;
}

The '?' appears but clearly does not have 20ex size. Why not? Tested in Firefox and Chrome.

spraff
  • 29,265
  • 19
  • 105
  • 197

6 Answers6

130

Note: The ::before and ::after pseudo-elements are actually laid display: inline; by default.

Change the display value to inline-block for the width & height to take effect while maintaining inline formatting context.

a.infolink::before {
    content: '?';
    display: inline-block;
    background: blue;
    color: white;
    width: 20px;
    height: 20px;
}

http://jsfiddle.net/C7rSa/3/

Jason Yaraghi
  • 51,338
  • 11
  • 87
  • 88
  • Nice solution..but This does not work when the content has a base64 image string...tested on firefox 45.3 – repzero Dec 02 '16 at 03:24
  • have you succeed with base64 images? – Webwoman Jun 12 '19 at 19:59
  • @Webwoman: Please be more specific -- if you're referring to controlling the image size through width / height then that's not the way it's supposed to work. Those attributes only control the sizing on the pseudo-element itself, not its content. – Jason Yaraghi Jun 15 '19 at 14:06
11

::before and ::after pseudo-elements are laid inline by default, so width and height won't take effect.

Set it to display: inline-block and it should work.

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
3

Use this if you have image in container or CSS white-space: nowrap; property

body::before{ 
    content:url(https://i.imgur.com/LJvMTyw.png);
    transform: scale(.3);
}
1

add display:block;

demo

p > a.infolink::before {
    display:block;
    content:'?';
    background: blue;
    color: white;
    width: 20ex;
    height: 20ex;
    border:1px solid #000;
}
NoobEditor
  • 14,239
  • 13
  • 66
  • 102
1

I can get it to work but not using a percentage in width. Pixels work fine

visibility: visible;
content: "stuff";
min-width: 29px;
width: 100%;
float: left;
position: relative;
top: -15px;
left: 0;
e11world
  • 101
  • 1
  • 9
  • That's usually because you haven't set a width on the element creating the pseudo-element. Percentages aren't any different in this case. – BoltClock Apr 17 '15 at 05:47
0

For me it worked when I used display: block.

Yuivae
  • 21
  • 3