将较大元素置于较小容器元素内

时间:2014-08-07 15:44:35

标签: html css

如何在不掩盖下方段落的情况下使图像居中? position: absolute;float: left;都会导致问题。

<p>This is the first paragraph</p>
<p><img src="http://placekitten.com/600/280"/></p>
<p>Paragraph 3</p>

假设以下CSS:

p { width: 100px; margin: 0 auto}

我还想确保较大的img元素不是overflow:hidden标记的p。我希望看到完整的图像,即使它太大了。

Example jsfiddle

3 个答案:

答案 0 :(得分:5)

如果您需要保留固定宽度段落,可以使用以下内容使图像居中:

img {
    -webkit-transform:translateX(-50%);
       -moz-transform:translateX(-50%);
        -ms-transform:translateX(-50%);
         -o-transform:translateX(-50%);
            transform:translateX(-50%);
    margin-left:50%;
}

答案 1 :(得分:0)

使用Jquery ......

小提琴:http://jsfiddle.net/remix1201/9twojm9g/6/

HTML:

<p>This is the first paragraph</p>
<p class="center"><img src="http://placekitten.com/600/280"/></p>
<p>Paragraph 3</p>

CSS:

p { max-width: 100px; max-height: 300px; background: #eee; padding: 1em; margin: 0 auto}

JS:(jquery)

var getContWidth = $("p").width();
var getImgWidth = $("p.center img").width();
var adjustMargin = (getImgWidth - getContWidth)/2;
$("p.center img").css("margin-left","-" + adjustMargin + "px");

答案 2 :(得分:0)

你的意思是like this

我采取了不同的方法,并希望它有所帮助。如果这对您有用,请告诉我。

<div class="container">
    <p>This is the first paragraph</p>
    <img src="http://placekitten.com/600/280"/>
    <p>Paragraph 3</p>
</div>

body {
    background-color: white;
}
.container {
    width:auto;
    margin:auto;
    background-color: #eee;
}
p { 
    padding: 1em; 
    margin: 0 auto;
    text-align: center; }

img {
    /* position: absolute; left: 0; */
    /* position: absolute; float: left; */
    display:block;
    margin:auto;
}
相关问题