Html 如果父对象较小,如何使图像居中?
我目前正在尝试一个响应设计。 当父div变小时,我需要保持图像居中 如图所示: 我不想把它作为背景。 以下代码将始终将其放置在div框的左上角Html 如果父对象较小,如何使图像居中?,html,css,Html,Css,我目前正在尝试一个响应设计。 当父div变小时,我需要保持图像居中 如图所示: 我不想把它作为背景。 以下代码将始终将其放置在div框的左上角 <div id="img_wrap"> <img src="test.png" id="img" /> </div> <style type="text/css"> #img_wrap { overflow: hidden; text-align: cent
<div id="img_wrap">
<img src="test.png" id="img" />
</div>
<style type="text/css">
#img_wrap {
overflow: hidden;
text-align: center;
}
</style>
#img_包装{
溢出:隐藏;
文本对齐:居中;
}
这是一个
诀窍在于,图像绝对位于中心,其父容器宽度的50%,然后通过变换向左移动其自身宽度的50%。以下是解决方案,以使图像响应
<div id="img_wrap">
<img src="test.png" id="img" />
</div>
<style type="text/css">
#img_wrap{
position:relative
}
#img_wrap img{
max-width:100%;
height:auto;
margin:0 auto;
display:block;
}
</style>
#img_包装{
职位:相对
}
#img_包装img{
最大宽度:100%;
高度:自动;
保证金:0自动;
显示:块;
}
希望它有帮助…如果旧浏览器兼容性不是问题,您可以使用以下方法
#img_wrap img
{
display:flex;
-ms-flex-pack:stretch;
-webkit-box-pack:stretch;
justify-content:center;
}
用于使图像居中
<div id="img_wrap">
<img src="http://placehold.it/350x150" id="img" />
</div>
<style type="text/css">
#img_wrap{
position: relative;
width: 200px;
height:150px;/*give the image height*/
background: red;
overflow:hidden;
display: inline-block;
}
#img{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>
#img_wrap{
位置:相对位置;
宽度:200px;
高度:150px;/*给出图像高度*/
背景:红色;
溢出:隐藏;
显示:内联块;
}
#img{
位置:绝对位置;
左:50%;
转化:translateX(-50%);
}
这是演示,这不是问题所在。
<div id="img_wrap">
<img src="http://placehold.it/350x150" id="img" />
</div>
<style type="text/css">
#img_wrap{
position: relative;
width: 200px;
height:150px;/*give the image height*/
background: red;
overflow:hidden;
display: inline-block;
}
#img{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>