I have a parent, that is 100% viewport height, and in this I have an img, the img size is to its parent.
Is there any way to vertically center the image without having to use static height and width for it?
codepen: http://codepen.io/pen/
I have a parent, that is 100% viewport height, and in this I have an img, the img size is to its parent.
Is there any way to vertically center the image without having to use static height and width for it?
codepen: http://codepen.io/pen/
Hi,
Try use the css code from this example:
<style type="text/css"><!--
div.container {
height: 12em;
border: 2px dotted blue;
display: table-cell; /* forms as a table cell */
vertical-align: middle; /* center vertically */
text-align: center; /* center horizontally */
padding: 3px 4px;
}
--></style>
<div class="container">
<img src="image.jpg" alt="Text for image" width="120" height="60" /><br/>
This line of text and the image above are vertically and horizontally centered.
</div>
Your link isn’t working I’m afraid.
As mentioned above you can use display:table-cell to vertically align content and will work in IE8+ (+all non IE).
Isn’t this the same question you answered in this thread which received much the same answer ?
No it is not the same, at least I don’t think so.
Now I want to vertically center a dynamic image, the image-size is responsive to its parent, which is 100% viewport height. The image has 70% width as its only size-value.
I have tried using table, table-cell but it doesn’t seem to work in this case.
.parent{
height: 100%;
display: table;
}
img{
width: 70%;
display: table-cell;
vertical-align: middle;
}
Do you suppose you can post another link to codepen? or maybe the same code in a working page (starts with <doctype, ends with </html>) here?
The image would need to be in a container as display:table-cell won’t work for an image as it isn’t a container for content (its a replaced element). Place the image in a container that is display:table-cell.
working example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<style type="text/css">
html, body {
margin:0;
padding:0;
height:100%;
}
.parent {
height: 100%;
width:100%;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
text-align:center;
}
img {
width: 70%;
height:auto;
vertical-align: middle;
}
</style>
</head>
<body>
<!-- IE8+ only (+ all other modern browsers)-->
<div class="parent">
<div class="child"><img src="http://placehold.it/350x150" alt="vertical image"></div>
</div>
</body>
</html>