Css center img in body

Выравнивание картинки по центру HTML и CSS

Выравнивание картинки HTML

Довольно часто, при верстке сайтов веб-разработчик сталкивается с необходимостью выравнивания изображений по центру. И если для опытного разработчика это не является проблемой, то у начинающего это может вызвать некоторые трудности.

Я покажу вам несколько способов выравнивания картинки по центру html и css , которые вы сможете использовать в зависимости от ситуации.

Выравнивание картинки HTML

Кода вы верстаете страницу, и в каком-то единичном случае вы заранее знаете, что данное изображение должно быть по центру блока, то вы можете сделать выравнивания картинки по центру в html коде, обернув картинку в тег

с определённым классом, и используя тег , задать для этого класса css-свойство text-align:

Или же можно сделать еще проще и добавить в тег атрибут style:

Выравнивание картинки по центру CCS

В случае если у вас есть несколько изображений, которые нужно выровнять по центру, то лучше подойдёт выравнивание картинок по центру путём внесения правок в файл CSS-стилей страницы или сайта. Для этого нужно присвоить изображению класс и дописать показанные ниже css-свойства.

Читайте также:  Linked lists java example

Этот способ выравнивания картинки css работает практически всегда. Задавать изображению класс не обязательно. Вы можете обратиться к нему через класс блока в котором оно находится. Например:

Так же можно воспользоваться альтернативным вариантом выравнивания картинки по центру, обернув изображение в абзац тегом

и, по аналогии с вариантом для HTML, задать абзадцу свойство text-align:center.

С помощью показанных в этой статье способов выравнивания картинок в html и css вы сможете выровнять нужное вам изображение практически в любой ситуации. В своей практике я стараюсь чаще использовать вариант с использованием text-align:center; или margin:auto, в зависимости от ситуации.

На этом я, пожалуй, закончу статью. Надеюсь, данная статья поможет вам разобраться с выравниванием картинок в html и css и вы сможете подобрать для себя наиболее удобный вариант.

Не забывайте делиться статьей в социальных сетях и оставлять комментарии, а так же заходите на мой канал на YouTube, где вы найдете много интересных видео по разработке сайтов, обзору полезных плагинов и скриптов.

Желаю вам успехов в создании своего сайта! До встречи в следующей статье!

С уважением Юлия Гусарь

Источник

How to Center an Image Vertically and Horizontally with CSS

Cem Eygi

Cem Eygi

How to Center an Image Vertically and Horizontally with CSS

Many developers struggle while working with images. Handling responsiveness and alignment is particularly tough, especially centering an image in the middle of the page.

So in this post, I will be showing some of the most common ways to center an image both vertically and horizontally using different CSS properties.

Here’s an interactive scrim about how to center an image vertically and horizontally:

I’ve gone over the CSS Position and Display properties in my previous post. If you’re not familiar with those properties, I recommend checking out those posts before reading this article.

Here’s a video version if you want to check it out:

Centering an Image Horizontally

Let’s begin with centering an image horizontally by using 3 different CSS properties.

Text-Align

The first way to center an image horizontally is using the text-align property. However, this method only works if the image is inside a block-level container such as a :

Margin: Auto

Another way to center an image is by using the margin: auto property (for left-margin and right-margin).

However, using margin: auto alone will not work for images. If you need to use margin: auto , there are 2 additional properties you must use as well.

The margin-auto property does not have any effects on inline-level elements. Since the tag is an inline element, we need to convert it to a block-level element first:

Secondly, we also need to define a width. So the left and right margins can take the rest of the empty space and auto-align themselves, which does the trick (unless we give it a width of 100%):

Display: Flex

The third way to center an image horizontally is by using display: flex . Just like we used the text-align property for a container, we use display: flex for a container as well.

However, using display: flex alone will not be enough. The container must also have an additional property called justify-content :

The justify-content property works together with display: flex , which we can use to center the image horizontally.

Finally, the width of the image must be smaller than the width of the container, otherwise, it takes 100% of the space and then we can’t center it.

Important: The display: flex property is not supported in older versions of browsers. See here for more details.

Centering an Image Vertically

Display: Flex

For vertical alignment, using display: flex is again really helpful.

Consider a case where our container has a height of 800px, but the height of the image is only 500px:

Now, in this case, adding a single line of code to the container, align-items: center , does the trick:

The align-items property can position elements vertically if used together with display: flex .

Position: Absolute & Transform Properties

Another method for vertical alignment is by using the position and transform properties together. This one is a bit complicated, so let’s do it step by step.

Step 1: Define Position Absolute

Firstly, we change the positioning behavior of the image from static to absolute :

Also, it should be inside a relatively positioned container, so we add position: relative to its container div.

Step 2: Define Top & Left Properties

Secondly, we define the top and left properties for the image, and set them to 50%. This will move the starting point(top-left) of the image to the center of the container:

Step 3: Define the Transform Property

But the second step has moved the image partially outside of its container. So we need to bring it back inside.

Defining a transform property and adding -50% to its X and Y axis does the trick:

There are other ways to center things horizontally and vertically, but I’ve explained the most common ones. I hope this post helped you understand how to align your images in the center of the page.

If you want to learn more about Web Development, feel free to visit my Youtube Channel for more.

Источник

Absolute Center (Vertical & Horizontal) an Image

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

 
columna uno
columna dos, la cual es bastante más alta que la anterior, y además la podemos hacer todavía más alta y la columna 1 ya no se centra
div.horizontal < display: flex; justify-content: center; >div.vertical < display: flex; flex-direction: column; justify-content: center; > 

good one! but the problem is that if you re size the browser you can’t scroll to the top. i.e if i have a menu on top i cant view it!

Why does everyone in the universe write background shorthand wrong? This is the correct way and the only way that works in ALL browsers that support background shorthand: background: #FFF url() repeat fixed left top; /rant

Craig, syntactically, you can have your properties in any arrangement: background: #fff url() fixed left top; is essentially the same as background: url() fixed 0 0 #fff; either way you look at it, it’s doing the same exact thing.

#arrr < position:absolute; top:0; left:0; width:100%; height:100%;>#black-flag < position:absolute; left:50%; bottom:145px;>#black-flag img

YOU ARE A KING MAN I would advice THIS PAGE for anyone whos searching for a solution regarding absolute centering of Image inside a DIV. WOOOOW!

what happen when you have different image size but whatever the image sizes you want all them in center. normally in jquery gallery case. i am struggling with this one from last two days. any help will be highly appreciated.

 document.getElementById('myimage').style.margin-top = document.getElementById('myimage').style.height / 2; document.getElementById('myimage').style.margin-left = document.getElementById('myimage').style.width/ 2; 

and if you wanted to do a bunch of them you would have to make an array maybe and cycle through them? O.o anyone else?

.
What about a pure CSS solution for vertically centering an image in a div that is POSITION:FIXED
.
Thanks a lot!

Hi, I have posted about 50 post to my blog. Now I have to change my template blog with a new one. I have upload the picture too.
The problem with my new template is my picture that I have uploaded before its not in the position I wanted. I have to re-upload the picture so its fix to my new template. Is there any can help me with this. So the picture that I have upload before its force to (300X300 pixel). Thank you before.

Here’s a simple jQuery code that checks the image size and then centers it… perfect for when you don’t know what the size of the image would be. https://github.com/devasaur/vlign.js/blob/master/vlign.js

I LOVE YOU!! Ahem, thanks heaps. I was trying to figure out how to place a graphic using absolute position on a centered body container. I realized you made the graphic centered by ‘left: 50%’ and then using my container width I divided by 2 and altered the measurements to get a perfect fit ;). ‘left: 50%’ is a very important element when using absolute position. Dammit, if I only knew this before then I wouldn’t change my design and css code :(. Oh well, you live and learn 😀 Thanks again and much appreciated.
CHEERS 🙂

I want an image in the background of my webpage (top center). Different image on every page.
On top of that I want to have a 1000px wide Div in the center of the page with the content.
I want it all to stay in the middle when I resize the browser-window.
How?

 position: relative; top: 50%; margin-top: -25%; 

This worked for me to align vertically center. I can’t use half height bacuase i dont know the height. So i used percentage

Thank you, Matthew Buchanan! This is perfect — nice and clean, and works for varying image sizes. It works for me in Firefox, Chrome, Safari, Opera, and IE 8 and 9.

Hey Matthew it worked for me to center image both vertically and horizontally within a container. Thanks 🙂

@charset "utf-8"; /* CSS Document */ * < margin:0; padding:0; >html, body < height: 100%; min-height:100% !important; width:100%; >#cuerpo < position:absolute; top: 50%; /*esta a la mitad*/ margin-top: -25%; /*le resta la mitad del alto*/ width: 700px; height: 500px; width: 100%; >#header < position:relative; margin: 0 auto 0 auto; width: 700px; height: 106px; background:#09F; >#contenido

Thanks for the tutorial, I am trying to place a paragraph below the centralised image, but when I do this the paragraph remains at the top left hand side of the browser window. Is there a way around this?

Based on Chris’ table approach, this worked great for me… html, body, #wrapper <
height:100%;
width: 100%;
margin: 0;
padding: 0;
border: 0;
>
#wrapper td <
vertical-align: middle;
text-align: center;
> .content <
width: 600px;
height: 400px;
background-color: red;
margin-left: auto;
margin-right: auto;
> And the html…

Great article! I love your site, it’s bookmarked : )
I use your method of absolute centering in all my websites.

/* Make the height 100% */
#container ul li display:inline-block;
height:100%;
>
/* Then vertical-align the crap outta it */
#container ul li img vertical-align:middle;
>
/* NOTE: The images don’t have fixed sizes either 🙂 This works in Firefox, been using it for a while so I must have cross browser tested it but can’t remember anymore. Give it go! */

Better and complete: style for a extensible box with title text and one image inside.
The position: relative and the width are not an obligation. div.frameStretch -moz-border-image: url(yourimageborder.png) 24 stretch; -moz-border-radius: 24px;
-webkit-border-image: url(yourimageborder2.png) 24 stretch; -webkit-border-radius: 24px;
-o-border-image: url(.yourimageborder.png) 24 stretch; -o-border-radius: 24px;
-ms-border-image: url(yourimageborder.png) 24 stretch; -ms-border-radius: 24px;
border-image: url(yourimageborder.png) 24 fill stretch; border-radius: 24px;
box-pack: center; box-shadow: 0px 1px 3px #122c53; text-shadow: -1px -1px 1px #cccccc, 1px 1px 1px #ffffff;> /* — For the title in the box — */
div.frameStretch h2
/* — To one image inside, vertical align, at right of the box —*/
div.frameStretch img

That background image is simply a brilliant kiss technique. Just wanted to drop a line, to say thanks a lot for this and so many other useful posts.

Hello, it’s uses basically a how center images , and it can take a server timestamp to start with. The css can also be easily modified to one’s own likings. http://www.phphunt.com/111/how-to-center-images

Hi Chris – or any genius out there, is there a “responsive” way of doing this? So when you resize your browser using “img” for the images to resize, is there a way to center it inside a div both vertically and horizontally?

Источник

Оцените статью