Reputation: 87
I can't figure how to select element in CSS.
<div class="text">
<img src="./img1.jpg">
<p>Lorem</p>
</div>
<br>
<div class="text">
<img src="./img2.jpg">
<p>Lorem</p>
</div>
How do I select every second image in the text div? I want for 1st one to float left, and for the second to float right. Whatever I try they are both floating left. As I can understand odd selector, just selects both of them.
img:nth-of-type(even){
float: right;
}
img:nth-of-type(odd){
float: left;
}
Upvotes: 0
Views: 267
Reputation: 14312
Firstly, the images are all floating to the left because every image is the first of type in its container. What you really want the image in every odd/even div to float to the left/right:
.text:nth-of-type(even) img{ float: right; }
.text:nth-of-type(odd) img{ float: left; }
You also need to clear your floats for the divs to stack properly. You can do this using the clearfix solution on the container of the floating elements, e.g.
.text:after {
content: "";
display: table;
clear: both;
}
Working example:
/* alternate the display between odd & even containers */
.text:nth-of-type(even) img{
float: right;
}
.text:nth-of-type(odd) img{
float: left;
}
.text {
margin-bottom: 20px;
}
/* clearfix to make each container fully contain its floated elements */
.text:after {
content: "";
display: table;
clear: both;
}
/* for testing so we can see where image would be */
img { height:100px; width:100px; background: #ccc;}
.text { background:#eee;}
<div class="text">
<img src="./img1.jpg">
<p>Lorem</p>
</div>
<div class="text">
<img src="./img2.jpg">
<p>Lorem</p>
</div>
And of course don't use the same id, as everyone has been pointing out!
Upvotes: 0
Reputation: 1970
First, id
is an unique identificator and should be used only once per page. You'd better change it to class
. And <br>
tag is unnecesary in this example, you can style any margins with css:
<div class="text">
<img src="./img1.jpg">
<p>Lorem</p>
</div>
<div class="text">
<img src="./img2.jpg">
<p>Lorem</p>
</div>
Then, images inside every odd and even blocks can be styled as:
.text:nth-child(even) > img {
float: left;
}
.text:nth-child(odd) > img {
float: right;
}
Upvotes: 1