Reputation: 563
I want to place a child element vertically with the parent element
<!DOCTYPE html>
<html>
<head>
<title>Jajal</title>
<style type="text/css">
#body {
font-family: sans-serif, arial, 'Roboto';
}
#outer {
width: 280px;
background-color: white;
height: 253px;
background-color: #f0f0f0;
}
.imgbox {
height: 174px;
width: 270px;
overflow: hidden;
display: table;
margin: 0 auto;
background-color: black;
text-align: center;
}
.img_content {
max-height: 174px;
max-width: 270px;
margin: 0 auto;
vertical-align: middle;
display: table-cell;
}
.titlebox {
max-width: 270px;
text-align: center;
}
.title {
font-weight: 900;
font-size: 14px;
}
</style>
</head>
<body>
<div id="outer">
<div class="imgbox">
<img class="img_content" src="http://lorempixel.com/700/100" alt="coba">
</div>
<div class="titlebox">
<p class="title">Lorem ipsum Amet</p>
</div>
</div>
</body>
</html>
Why the img_content class doesn't place verticaly middle with imgbox class when the image is to width?
Upvotes: 2
Views: 1353
Reputation: 241
There are a lo of ways you could do this. You could wrap he img tag in a div with class of say, wrapper. then the wrapper div would have styling like so :
.wrapper {
vertical-align: middle;
display: table-cell;
}
, and remove the display:table-cell, and vertical-align:middle from the image
Working fiddle using another way if you dont wan any changes in the existing CSS https://jsfiddle.net/mfkxq728/
Also,you could use either of flex(Browser support might be a concern) or the good old relative-absolute position with a translate-Y. The translate-Y would however need browser prefixes for consistent performance.
Cheers !!
Upvotes: 0
Reputation: 39342
Use css3 flexbox
. Following css should be added on parent element.
.parent {
justify-content: center;
align-items: center;
display: flex;
}
#body {
font-family: sans-serif, arial, 'Roboto';
}
#outer {
width: 280px;
background-color: white;
height: 253px;
background-color: #f0f0f0;
}
.imgbox {
justify-content: center;
align-items: center;
display: flex;
height: 174px;
width: 270px;
overflow: hidden;
margin: 0 auto;
background-color: black;
text-align: center;
}
.img_content {
max-height: 174px;
max-width: 270px;
}
.titlebox {
max-width: 270px;
text-align: center;
}
.title {
font-weight: 900;
font-size: 14px;
}
<div id="outer">
<div class="imgbox">
<img class="img_content" src="http://lorempixel.com/700/100" alt="coba">
</div>
<div class="titlebox">
<p class="title">Lorem ipsum Amet</p>
</div>
</div>
Upvotes: 1
Reputation: 550
Add following CSS:
.imgbox {
height: 174px;
width: 270px;
overflow: hidden;
margin: 0 auto;
background-color: black;
text-align: center;
position: relative;
}
.img_content {
max-height: 174px;
max-width: 270px;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
}
Upvotes: 1