Html css centering img

How to Center An Image Horizontally and Vertically in CSS

How many times have you had to Google ‘how to center an image in CSS’? It has been too many times to count for me. As a result, I wanted make a snippet on all the ways you can center an image in CSS.

The purpose of the snippet post is so you can grab the code at the top of the post. This will allow you to quickly cut and paste the code you need to center CSS images.

For this snippet we are going to refer to the HTML below.

div class="img-container">
img class="lazyload .center" src="path/to/image" />
div>

CSS Image Center Horizontally

Currently with CSS images there are three ways to center an image horizontally. I’ll go over the three ways, the pro’s and con’s for each so that you can center an image with CSS in any situation.

Center CSS Image with Text Align

.center
text-align: center;
>

It is important to note with this method that the text-align property only works on block level elements.

Center CSS Image with Margin

.center
display: block;
margin: auto;
width: 50%;
>

Centering an image with margin:auto is a great way to get the job done. However, you need to ensure it is used with two other properties.

The first is display:block as the margin:auto property only works on block level elements. As, Img elements are inline elements you will need to convert them to block level elements.

The second property is the width property. In order for the margins to move to the center you need to ensure there is empty space. Therefore, you must set the width to less than 100%.

Center CSS Image Horizontally with Flex

.img-container
display: flex;
justify-content: center;
>
.img
width: 50%;
>

Setting the parent container of the image to display:flex allows you to center the image horizontally. In order to move the image to the center of the container you must specify the justify-content property to have a value of center .

Like with the margin horizontal centering method, you need to ensure you set the image to less than 100% of the width of the parent container.

Just note with this method that everything else in the parent container will be centered horizontally.

Alright those three methods should allow you to center any image horizontally. Let’s look at how to center an image vertically.

CSS Image Center Vertically

Notably with CSS images there are two key ways to center an image vertically. I’ll go over the two ways, the pro’s and con’s for each so that you can center an image vertically with CSS in an situation.

Center CSS Image with Position Absolute

.img-container
position: relative;
>
.center
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
>

To center a CSS image vertically, you can use the position property with a value of absolute on the img element. The first thing you need to do, is to set the parent container to have a position value of relative . This is a must and you can learn why in my ridiculously simple guide to the position property.

Next, you set the left and top properties to 50%. What this means is that you line up the left and top edges of the image with the center of the browser. However, this actually makes the image appear to be off-center.

Therefore, you use the transformation property with the translate method to move the div -50% along the x and y axis. This will have the image aligned nicely to the vertical center of the parent elements position on the page.

Center CSS Image Vertically with Flex

.img-container
display: flex;
align-items: center;
>
.center
width: 50%;
>

As with the horizontal centering we can center an image using flex-box. This time in order to move the image to the center of the container you must specify the align-items property to have a value of center .

Like with the margin horizontal centering method, you need to ensure you set the image to less than 100% of the width of the parent container.

Again, with this method everything else in the parent container will be centered vertically.

Center CSS Image Vertically and Horizontally

So far we have seen how to center a CSS image either horizontally or vertically. But, we have not seen how to do both at once.

Let’s see how to center an image horizontally and vertically at the same time.

.img-container
display: flex;
justify-content: center;
align-items: center;
>
.center
width: 50%;
>

We can use flex-box to center an image horizontally and vertically. To do so we must use both the justify-content and align-items property on the parent container of the image. All we then have to do is give them both the value of center and bobs your uncle, that image is centered both horizontally and vertically.

These are the most common methods for centering an image both horizontally and vertically in CSS. In most cases, this will be enough for you to get your image to the position you want on the page. Of course there are other methods and I’d love for you to DM me on twitter to let me know what they are.

If you enjoyed this post you might also like my posts on…

Peter Lynch

Web Developer & Bootcamp grad who wants to learn as much as he can check me out on twitter.

Starting from the bottom newsletter

This newsletter is a record of my journey as an indie hacker, developer, entrepreneur, and human. Delivered straight to your inbox each Sunday.

Источник

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

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

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

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

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

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

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

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

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

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

Этот способ выравнивания картинки 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.

Источник

Читайте также:  Вертикальное выравнивание посередине css
Оцените статью