CSS weekly #2: An image on the left, text on the right
Image on the left and text on the right is a common pattern but don’t use it too often and when one of friends ask me how she could make this I couldn’t say it right away. But it’s an easy question, a beginning level with several methods. So let’s take a look at how we could solve “an image on the left and text on the right”.
#1. Float and inline
In this example we have two elements inside a container — img
and div
element with h1
and p
elements inside it. float: left
is an old and simple method. This method allows your text to float around the image. Medium uses this method.
.container {
&__image {
width: 250px;
float: left;
}
&__text {
display: inline;
}
}
#2. Inline-block and percentage
We also can make this layout without floating effect using inline block and percentage like two columns.
.container {
&__image {
display: inline-block;
vertical-align: top;
width: 46%;
}
&__text {
display: inline-block;
width: 46%;
@media (max-width: 620px) {
width: 100%;
}
}
}
We need to add vertical-align: top
to position the image on top. Make the width of each element smaller than 50% to prevent line-break.
#3. flex-box
Make this layout using flexbox. Don’t forget to include object-fit: contain
to prevent image stretching and like with float: left
we need to position the image on top by using align-self: flex-start
.
#4. Grid
Yes we also could do it using Grid layout but to me it’s like to crack a nut with a sledgehammer, so, see you next week :-)