Bob
Bob

Reputation: 1085

Divs with fixed and dynamic width and vertically centered image

I have the following HTML

<div class="parent">
    <div class="left-colum">Some paragraphs of text</div>
    <div class="right-column"><img src="image.jpg"></div>
</div>

The right-column has the width of the image, but since it holds different size images its width is unknown. I want the left-column to take whatever is needed but with a max-width of 150px. I also want the image in the right-column centered vertically.

In the end it should look like the example below, but I have a hard time time getting this together. How would I do this?

enter image description here

edit: I have the following CSS, but the right-column isn't at 100% height so I can't start trying to vertically center the image yet:

.parent{
    position: relative;
    height: 100%;
}
.left-colum{
    float: left;
    max-width: 150px;
}
.right-column{
    float: right;
    height: 100%;
}

Upvotes: 0

Views: 36

Answers (2)

Farzad Yousefzadeh
Farzad Yousefzadeh

Reputation: 2551

Use flex display on columns and set display:flex; align-items:center; justify-content: center on right div and max-width: 150px; on left div. Also be aware of vendor prefixes for browsers in order to properly use flex property.

.parent {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.left-column {
     max-width: 150px;
    display: flex;
}
.right-column {
    display: flex;
    justify-content: center;
    align-items: center;
    display:center;
}

Upvotes: 1

Stickers
Stickers

Reputation: 78706

You could use nested flexbox see the comments inline.

body {
    margin: 0;
}
.parent {
    display: flex;
    height: 100vh; /*viewport height*/
}
.left-column {
    background: pink;
    max-width: 150px;
}
.right-column {
    background: gold;
    flex: 1; /*expand*/
    display: flex;
    justify-content: center; /*center x*/
    align-items: center; /*center y*/
}
<div class="parent">
    <div class="left-column">Some paragraphs of text</div>
    <div class="right-column">
        <img src="//dummyimage.com/100">
    </div>
</div>

Upvotes: 2

Related Questions