When I place svg
image next to text, with vertical-align: middle;
, then it aligns pretty nicely. However, if I use svg
in the ::after
pseudo-element, then the results are not as expected.
Furthermore, when I click on text to remove its content, then remaining svg
element still keeps its unaligned position:
Here is the code:
document.getElementById('em1').addEventListener('click', e => { (e.target || e.srcElement).innerText = ''; }); document.getElementById('em2').addEventListener('click', e => { (e.target || e.srcElement).innerText = ''; }); document.getElementById('em3').addEventListener('click', e => { (e.target || e.srcElement).innerText = ''; });
* { vertical-align: middle; } div { background-color: yellow; } em { background-color: pink; cursor: pointer; font-size: 41px; } #em2::after, #em3::after { content: url("data:image/svg+xml,%3Csvg%20width%3D%22110%22%20height%3D%2246%22%20viewBox%3D%220%200%20110%2046%22%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20style%3D%22fill%3A%23f00%3Bstroke-width%3A0%22%20d%3D%22M%200%2C0%20H%20110%20V%2046%20H%200%20Z%22%20%2F%3E%3C%2Fsvg%3E"); } #em3::after { vertical-align: middle; }
<div> <em id="em1">text #1</em><svg width="110" height="46" viewBox="0 0 110 46" version="1.1" xmlns="http://www.w3.org/2000/svg"><path style="fill:#f00;stroke-width:0" d="M 0,0 H 110 V 46 H 0 Z" /></svg> </div> <hr> <div> <em id="em2">text #2</em> </div> <hr> <div> <em id="em3">text #3</em> </div>
How to make this work, what has to be adjusted, and why? Why are not ::after
pseudo-elements aligned automatically with their “parents”?
Advertisement
Answer
It can be solved giving vertical-align: text-bottom; height: 46px; display: inline-block;
to the after
pseudo-elements:
document.getElementById('em1').addEventListener('click', e => { (e.target || e.srcElement).innerText = ''; }); document.getElementById('em2').addEventListener('click', e => { (e.target || e.srcElement).innerText = ''; }); document.getElementById('em3').addEventListener('click', e => { (e.target || e.srcElement).innerText = ''; });
* { vertical-align: middle; } div { background-color: yellow; } em { background-color: pink; cursor: pointer; font-size: 41px; } #em2::after, #em3::after { content: url(data:image/svg+xml,%3Csvg%20width%3D%22110%22%20height%3D%2246%22%20viewBox%3D%220%200%20110%2046%22%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20style%3D%22fill%3A%23f00%3Bstroke-width%3A0%22%20d%3D%22M%200%2C0%20H%20110%20V%2046%20H%200%20Z%22%20%2F%3E%3C%2Fsvg%3E); vertical-align: text-bottom; height: 46px; display: inline-block; }
<div> <em id="em1">text #1</em><svg width="110" height="46" viewBox="0 0 110 46" version="1.1" xmlns="http://www.w3.org/2000/svg"><path style="fill:#f00;stroke-width:0" d="M 0,0 H 110 V 46 H 0 Z" /></svg> </div> <hr> <div> <em id="em2">text #2</em> </div> <hr> <div> <em id="em3">text #3</em> </div>