[英]How to center image vertically in div
我有一个高度为100vh的div,因此它始终是浏览器屏幕的高度。 在此div内部,我想放置一个图像并将其垂直于其父对象居中。
高度是可变的,所以我不能使用固定边距。 我当前的标记如下:
的HTML
<div class="textportfolio">
<h1>This is a title</h1>
<p class="textbio-small">
The Roosevelt dime is the current ten-cent piece of the United States.
</p>
<img class="portfolio-slides-img" src="https://i.imgur.com/iheO43X.png">
</div>
CSS:
.textportfolio {
font-family: "Lora", serif;
margin: 5%;
background: #e9cca3;
height: 100vh;
}
img.portfolio-slides-img {
max-width: 40%;
max-height: 40%;
margin: 0 auto;
display: block;
}
有人知道如何根据浏览器高度将图像垂直居中吗?
这是代码片段
.textportfolio { font-family: "Lora", serif; margin: 5%; background: #e9cca3; height: 100vh } img.portfolio-slides-img { margin-top: 15%; max-width: 40%; max-height: 40%; margin: 0 auto; display: block; }
<div class="textportfolio"> <h1>This is a title</h1> <p class="textbio-small"> The Roosevelt dime is the current ten-cent piece of the United States. </p> <img class="portfolio-slides-img" src="https://i.imgur.com/iheO43X.png"> </div>
我使用以下CSS代码段:
.selector {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
应用于您的样本: https : //jsfiddle.net/nhdh8ycr/4/
在CSS中以事物为中心一直是争论不休的话题,人们权衡所有因素并争论最费解的方法是什么。
然后在2014年,一种叫做Flexbox的东西问世了,基本上使所有这些东西都过时了。
当容器display: flex
,将具有对齐其子代的属性。 您可以将其锚定在任一轴或两个轴的中间。
<div id="container">
<img src="https://i.imgur.com/i9xpVnQ.jpg" />
</div>
html, body {
height: 100%; /* required to make body occupy the full viewport by default */
}
#container {
height: 100%;
display: flex;
align-items: center; /* horizontal */
justify-content: center; /* vertical */
}
img {
height: 200px;
}
https://jsfiddle.net/5goboeey/1/
它非常方便,我认为它会继续受到关注,因为人们认为它不可能如此简单。
也许这个stackoverflow问题可以帮助您jsfiddle
代码是HTML
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=3 />
</div>
的CSS
.frame {
height: 25px; /* equals max image height */
line-height: 25px;
width: 160px;
border: 1px solid red;
text-align: center; margin: 1em 0;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}
尝试这个:
.textportfolio { font-family: "Lora", serif; margin: 5%; background: #e9cca3; height: 100vh; position: relative; } img.portfolio-slides-img { max-width: 40%; max-height: 40%; margin: 0 auto; display: block; position: absolute; right: 0; left: 0; top: 35% }
<div class="textportfolio"> <h1>This is a title</h1> <p class="textbio-small"> The Roosevelt dime is the current ten-cent piece of the United States. </p> <img class="portfolio-slides-img" src="https://i.imgur.com/iheO43X.png"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.