您的位置:首页 > Web前端 > CSS

如何让图片居中显示。让图片只适应居中。

2017-04-23 16:30 225 查看
方法一

margin设为auto,对浮动元素或绝对定位元素无效;

text-align:center 只能对图片,按钮文字等行内元素进行水平居中;(ie6,7中能对任何元素进行水平居中)

已知固定宽高

.out{
width:200px;
height:200px;
border:1px solid red;
position:relative;
}
.inner{
width:100px;
height:100px;
background:red;
position:absolute;
left:50%;
top:50%;
margin-top:-50px;
margin-left:-50px;
}

<div class="out">
<div class="inner"></div>
</div>


方法二

.out{
width:200px;
height:200px;
border:1px solid red;
position:relative;
}
.inner{
width:100px;
height:100px;
background:red;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;

}

<div class="out">
<div class="inner"></div>
</div>


方法三

.使用浮动配合相对定位进行水平居中,不需要固定的宽度。但是需要一个多余的元素包裹要居中的元素。

.out{
width:200px;
height:200px;
border:1px solid red;
}

//浮动居中的方法需要有这么一个包裹元素,需要浮动的就是这个元素
.wraper{
//在这个包裹元素上进行浮动,让他自适应内容宽度
float:left;
position:relative;
left:50%;              //相对定位到父元素宽度一半的地方
clear:both;
}
.child{
border:1px solid red;
position:relative;
left:-50%;
white-space:nowrap;
}

<div class="parent">
<div class="wraper">
<div class="child">居中</div>
</div>
</div>


方法四

下面是相对于浏览器居中代码,也就是说浏览器视口变化,图片也会相对其进行居中调整

我将其用在pc端

// 不需要设置 position:relative
.animate{position:absolute;top:50%;left:50%;margin:-100px 0 0 -150px; width:300px; height:200px; z-index:99;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css