width and height doesn't seem to work on :before pseudo-element

CssPseudo Element

Css Problem Overview


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.

Css Solutions


Solution 1 - Css

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/

Solution 2 - Css

::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.

Solution 3 - Css

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);
}

Solution 4 - Css

For me it worked when I used display: block.

Solution 5 - Css

If you set the element to position: relative and the pseudo to position: absolute, you can adjust the pseudo width and height in relation to the parent element size.

div {
    position: relative;
    width:400px;
    height:200px;
    padding: 0;
}

 div::before {
    position: absolute;
    width:100%;
    height: 100%
}

Solution 6 - Css

add display:block;

http://jsfiddle.net/C7rSa/4/"> demo

p > a.infolink::before {
    display:block;
    content:'?';
    background: blue;
    color: white;
    width: 20ex;
    height: 20ex;
    border:1px solid #000;
}

Solution 7 - Css

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionspraffView Question on Stackoverflow
Solution 1 - CssAdriftView Answer on Stackoverflow
Solution 2 - CssBoltClockView Answer on Stackoverflow
Solution 3 - CssDmytro YurchenkoView Answer on Stackoverflow
Solution 4 - CssYuivaeView Answer on Stackoverflow
Solution 5 - CssDevView Answer on Stackoverflow
Solution 6 - CssNoobEditorView Answer on Stackoverflow
Solution 7 - Csse11worldView Answer on Stackoverflow