Simple Layout with Floats
Now it's time to start putting elements next to each other rather than in just a big list that goes down the page. To do this, we need to understand how html likes to treat everything like text, and then work around it.
Goal
- Make a layout like this, with images on the left and text on the right
Example
![]() |
---|
Example on codepen: "Animals Listing: simple layout with floats": https://codepen.io/joe_bacal/pen/brNOZv |
Clues
You will need to nest divs within divs
Here we have an image inside a div inside another div
<div class="my-container">
<div class="some-class">
<img src="...">
</div>
</div>
Allow divs to slide next to eachother with widths and floats
- When you tell a div to
float
you are allowing it to "drift" left or right instead of flowing like regular text. - Nobody will float next to anyone else unless their widths are set
.animal {
text-align:center;
width:30%;
float:left;
}
.description {
width:70%;
float:right;
}
You will need to apply these CSS rules
box sizing:border-box
tells the browser to include padding when we size stuff
clear:both
tells the containers not to let stuff float up next to them if those elements are set to float
/*this makes padding not change element width*/
div {
box-sizing:border-box;
}
/*you can call your container divs anything you want*/
.your-container {
clear:both;
}
Complete Code
<h1>Animals Listing</h1>
<!-- first animal starts here -->
<div class="container">
<div class="animal">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Brown-White_Husky_Climbing.JPG/1920px-Brown-White_Husky_Climbing.JPG">
</div>
<div class="description">
<h2>Dogs</h2>
<p>Dogs are great pets. They love to play and they also like to protect the house.</p>
</div>
</div>
<!-- second animal starts here -->
<div class="container">
<div class="animal">
<img src="https://upload.wikimedia.org/wikipedia/commons/9/98/Alligator.jpg">
</div>
<div class="description">
<h2>Alligators</h2>
<p>Alligators are not good pets. They are not playful and
are too dangerous to have around the house.</p>
</div>
</div>
div {
box-sizing:border-box;
padding:12px;
}
.container {
clear:both;
}
.animal {
text-align:center;
width:30%;
float:left;
}
.animal img {
width:100%;
}
.description {
width:70%;
float:right;
}