简体   繁体   中英

Centering an image with varying width wider than parent container

I'm trying to build a blog with a middle column of text, with images also centered on the page. I'd like the text 600px wide, but images can be up to 1024px wide and I'd like them to be centered on the page.

My weird constraint is that I'm using the Shopify platform and my code gets generated like this (ie the img is inside ap tag)

    <div class="container">
     <p>Hello 123, this is a blog post..</p>
     <p><img src="//cdn.shopify.com/s/files/1/0296/9253/files/IMG_6009_1024x1024.JPG?14454" /></p>
     <p>This is also some text</p>
     </div>

So how do I write code that allows my images to hang outside the p tags when I don't know the images width? I could write a jQuery solution but ideally I'd write a CSS solution...

Thanks!

There are many ways to centre elements:

Margin way:

With a set width or display: inline-block; you can use:

margin-left: auto;
margin-right: auto;

text-align way:

With a set width or display: inline-block; you can add this to the parent:

text-align: center;

Absolute way:

position: absolute;
left: 50%;
margin-left: width/2;

or

position: absolute;
left: 50%;
transform: translate(0, -50%);

Also don't worry too much about ie7 and below as the the majority of people use higher versions of ie or a different browser though this should work up until ie6

Also if you just want to put it into HTML you can add this to the parent of the image:

align='center'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM