HTML图片大小调整和居中

3

我看了很多帖子,试图调整我的图像大小,但是不起作用,有人能帮我居中并使图像变小吗?

HTML:

<div id="mainBody">
<div id="image">
    <img src="http://s10.postimg.org/6b22cnbfd/jpg">
</div>

CSS:

.mainBody{
    width: 100%;
    margin-right: auto;
    margin-left: auto;}
.image {
    width: 60%;
    position: fixed;
    align-items: center;}
.image img{
    position: fixed;
    display:block;
    margin-left: auto;
    margin-right: auto;
    vertical-align: middle;}
'

是因为你在HTML中使用了id属性,而在CSS中却样式化了类吗? - Mihail Minkov
.mainBody -> 这里的 '.' 表示一个类,但是你在 HTML 中使用它作为 ID 而不是类。你应该使用 '#' 代替来表示 ID。(例如:#mainBody)其他情况也适用。 - bot
3个回答

0
你的 CSS 引用了 .image img,但实际上应该是 id 为 image,所以应该改成 #image img。
另外,你需要指定一个宽度属性: 可以使用 max-width:80% 或 width:400px。

0

它没有居中是因为它的位置被设置为固定的。对于固定位置元素,margin: 0 auto 是不起作用的。你需要将 left 设置为50%,然后使用负的 margin-left 将其拉回一半的宽度。例如:

img {
    position:fixed;
    width:300px;
    left:50%;
    margin-left:-150px;
}

http://jsfiddle.net/e24d0bx6/1/


0

我认为您可以使用position或margin,但如果您有许多不同大小的图像,则可能无法正常工作。 更好的方法是,我认为您应该使用background-image。就像这样:

Html

<div id="image">
</div>

CSS

#image {
    background-image: url(path/to/your/image);
    background-position: center;
    //set size of #image div like you want
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接