Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

html - center <IMG/> inside a <DIV> with CSS

I want to center image inside a div. The div has fixed width 300px. The image width is known only at runtime. It usually is bigger then 300px, so image should be centered and cut right and left. margin 0 auto does not work in this case.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">

div{width:300px;border:1px solid red; overflow:hidden}

img{
/* NOTE!!!!
margin:auto; doesn't work when image width is bigger than div width
image width is known only at runtime!!!
*/
}
</style>
</head>

<body>
<div>
    <img src="" />
</div>
</body>
</html>

Thanks for any css ideas


UPD This interesting task is followed here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Giving the div text-align: center should work. (You may have to add align='center' as a property for it to work in IE6, though.) Note: As pointed out by @streetpc, this method will not work properly if the image is wider than the container.

Alternatively, you could also have the image as a background image:

background-image: url(url);
background-position: center top;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...