I'm trying to get a CSS selector for <img>
elements on their own line but not an in-line <img>
. So it should match (example 1):
<p><img src="..."></p>
but not (example 2):
<p>Lorem <img src="..."> ipsum</p>
I tried img:only-child
-- because
This may be sufficient for your use case - it's drawback is that the img has a right hand margin in the img-only case. This may or may not matter to you. In the sense this is all within a p element I suspect it'll be OK as any following content will be on a newline.
* {
margin: 0;
padding: 0;
}
p::first-letter {
margin-left: 20px;
}
p {
margin-left: -20px;
}
p img {
margin: 0 20px;
}
<p><img src="https://picsum.photos/id/1015/100/100"></p>
<p>More than one word of text <img src="https://picsum.photos/id/1015/100/100">
</ "> and some more text</p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I think the CSS solutions are good. Especially @AHaworth because it also takes into account when there are more words in the text. Which is very probably the case. Therefore also thumbs up!
For the sake of completeness, I have added a Javascript solution here.
w = document.querySelectorAll('.wrapper')
w.forEach((el) => {
if (el.childNodes.length > 1) {
el.childNodes.forEach((e) => {
if( e.length === undefined) {
e.classList.add('addMargin')
}
})
}
})
.addMargin {
margin-left:20px;
margin-right:20px;
}
<p class="wrapper"><img src="https://picsum.photos/id/237/100/100"></p>
<p class="wrapper">Lorem <img src="https://picsum.photos/id/237/100/100"> ipsum bla</p>
<p class="wrapper">Lorem ipsum <img src="https://picsum.photos/id/237/100/100"> ipsum bla </p>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>