强制图像始终位于 div 的中间
Force an image to ALWAYS stay at the middle of a div
我正在寻找强制图像元素始终保持在 div 中间对齐的方法,即使 div 元素变得太小而无法正确居中图像。这是我想要做的事情的解释:Question.jpg
如果可能的话,我需要纯粹的解决方案CSS?
您可以这样做,使用显示 flex
。
div {
width: 100%;
height: 500px;
border: 1px solid gray;
display: flex;
align-items: flex-start;
text-align: center;
}
img {
align-self: center;
margin: 0 auto;
}
<div>
<img src="http://screenshots.en.sftcdn.net/en/scrn/323000/323026/angry-birds-theme-02-100x100.png" alt="">
</div>
使用以下网格布局和样式:
style{
.container{ max-width:800px; margin:0 auto;}
}
@media
only screen and (max-width:600px) {
.mCenter{margin:0 auto;}
.mImage600:{width:100%; height:auto;}
}
<div class=container>
<div class=mCenter>
<img class=mImage600 src 'img.jpg' width=600 >
</div>
<div>
使用这个居中技巧应该可以满足您的需求:
img {
position:relative; (or absolute, it depends on your needs)
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
无论容器大小如何,这都会使图像居中。但它不会调整图像的大小。根据你的那张照片,你似乎不想要那个。
img{
margin: 0 auto;
}
有帮助
我正在寻找强制图像元素始终保持在 div 中间对齐的方法,即使 div 元素变得太小而无法正确居中图像。这是我想要做的事情的解释:Question.jpg
如果可能的话,我需要纯粹的解决方案CSS?
您可以这样做,使用显示 flex
。
div {
width: 100%;
height: 500px;
border: 1px solid gray;
display: flex;
align-items: flex-start;
text-align: center;
}
img {
align-self: center;
margin: 0 auto;
}
<div>
<img src="http://screenshots.en.sftcdn.net/en/scrn/323000/323026/angry-birds-theme-02-100x100.png" alt="">
</div>
使用以下网格布局和样式:
style{
.container{ max-width:800px; margin:0 auto;}
}
@media
only screen and (max-width:600px) {
.mCenter{margin:0 auto;}
.mImage600:{width:100%; height:auto;}
}
<div class=container>
<div class=mCenter>
<img class=mImage600 src 'img.jpg' width=600 >
</div>
<div>
使用这个居中技巧应该可以满足您的需求:
img {
position:relative; (or absolute, it depends on your needs)
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
无论容器大小如何,这都会使图像居中。但它不会调整图像的大小。根据你的那张照片,你似乎不想要那个。
img{
margin: 0 auto;
}
有帮助