使用CSS进行图像居中和大小调整

时间:2014-09-08 13:58:53

标签: html css image position

我希望有一个页面显示尽可能大的图像但是整个图像在视图中,不改变图像的比例,并且以页面为中心(即带有边框或全宽的全高)边框顶部和底部)。有没有办法在CSS中完全做到这一点?我尝试了宽度/高度/最小宽度/最小高度属性的各种组合,但无法按照我的意愿显示它。

我还希望能够覆盖由带有背景图像的div组成的链接,该背景图像在悬停时更改,其代码如下所示。我希望它位于图像的右上角:

HTML:

<div class="imagecontainer">
    <img src='gallery/images/<?php echo $image;?>' max-height="100%" width="100%"/>
    <div class="backbuttoncontainer">
        <a class="gallerybackbutton" href="gallery/index.htm"></a>
    </div>
</div>

CSS:

.imagecontainer{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
.backbuttoncontainer{
    text-align:right;
    margin-top: 10px;
    margin-right: 10px;
    height: 38px;
    width: 100%;
    display: block;
}
.gallerybackbutton{
    background: url('icons/back_to_gallery.png') bottom;
    display: inline-block;
    height: 28px;
}
.gallerybackbutton:hover{
    background-position: 0 0;
}

3 个答案:

答案 0 :(得分:1)

也许这就是你想要的:JSFIDDLE,这里是如何:

为您想要的任何尺寸(200x200或400x200或200x400)创建图像容器,然后将图像放入容器中,并使用style

vertical-align: middle // to make your image centered vertically, but it's relative to the inline element, so if you don't have any text or set line-height for it's siblings, it doesn't work
max-width: 200px; // or your container width
max-height: 200px; // or your container height
// this style is used for my example with the container max-width and max-height set to 200px

然后在容器中添加此style

text-align: center; // to make it centered horizontally
width: 200px; // for example
height: 200px; // for example
border: 1px solid red; // only to show the container in this example
line-height: 200px; // this will make the inline element in the center from 200px, or so

或在此JSFIDDLE中使用pseudo element的其他方法,您需要制作一个容器和将要居中的图像:

<div class="block">
    <img src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-7.jpg" class="centered" />
</div>

pseudo element添加到容器block

.block:before {
    content:'';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    margin-right: -0.25em; // to remove the spacing that's created by inline-block
}

并为将要居中的图片添加style

.centered {
    display: inline-block;
    vertical-align: middle;
    max-width: 100%;
    max-height: 100%;
}

这里是css tricks: centering in the unknown

的解释

答案 1 :(得分:0)

要使用margin:auto,您必须具有静态宽度。 但是你的图像是一个像素图像,并且具有静态宽度。

只需将图片宽度和边距设置为自动:

.backbuttoncontainer{
    margin:auto;
    height: 38px;
    width: 100px;
}

答案 2 :(得分:0)

将图像设置为背景并尝试以下代码

class-name{
  background:url('1.jpg') no-repeat center center fixed ; 
  width:100%;
  height:auto;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size:cover;
  background-size: cover;

    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='1.jpg',sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='1.jpg',sizingMethod='scale')";