Issue
I am trying to figure out how to achieve the following.
I have an img
tag which has a given width
, and initially contains no src
. It also has a 2px black border.
I would like to give it an initial height that I can specify, but which switches to height:auto
once a src
is assigned (via a file input
).
Is this possible using only html & css?
Solution
This CSS will adjust the height of the containing div depending whether the img element has a src set or not.
It starts by setting the img to the width and height required. Then if there is a src attribute it changes height to auto. Then if the src attribute is empty it sets the height to the required default.
.container {
padding: 20px;
background: pink;
position: relative;
display: inline-block;
}
img {
height: 100px;
width: 200px;
}
img[src] {
height: auto;
border: solid 2px black;
}
img[src=""] {
height: 100px;
border: none;
}
<p>The container div is pink</p>
<p>There is no src in the img element</p>
<div class="container">
<img/>
</div>
<p>src in img element is set</p>
<div class="container">
<img src="https://picsum.photos/id/1015/200/300" />
</div>
<p>There is an empty src in img element</p>
<div class="container">
<img src="" />
</div>
The container div has been given a bit of padding so it can be seen behind the img just for this demo.
Answered By - A Haworth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.