- How to Center an Image in HTML
- Aligning in Text
- Aligning in a Center Tag
- Community Q&A
- CSS Image Centering – How to Center an Image in a Div
- How to Center a div using CSS
- How to Center an Image in a Div Horizontally with Text-align
- How to Center an Image in a Div Horizontally with Margin-auto
- How to Center an Image in a Div Horizontally with the Position and Transform Properties
- How to Center an Image in a Div Horizontally with Display-Flex
- How to Center an Image in a Div Vertically with Display-Flex
- How to Center an Image in a Div Vertically with the Position and Transform Properties
- How to Center an Image in a Div Horizontally and Vertically with Display-Flex
- How to Center an Image in a Div Horizontally and Vertically with the Position and Transform Properties
- Wrapping Up
- Как выровнять картинку по центру с помощью CSS
- Первый вариант
- Второй вариант
- Третий вариант
How to Center an Image in HTML
This article was co-authored by wikiHow staff writer, Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions.
This article has been viewed 163,212 times.
Image alignment is an important skill to learn when coding webpages. Unfortunately, as code changes, some HTML tags are deprecated and are not recognized by all web browsers. Try these methods to center an image in HTML. If they don’t work, consider coding in Cascading Style Sheets (CSS).
Aligning in Text
Don’t use the word “center” in your tag. In HTML coding, you can center text, but you must identify image alignment with the word “middle.” An image is not a line element, so it is identified in relation to other elements.
Start a new line of code. Use a paragraph tag to indicate that a text line is beginning. Start your tag with
then write your text.
Insert the image by typing gif”. Then include your image description by typing alt=”image description”.
- The “src” section tells the web page the URL of the image.
- The alt section tells the web page what it should be called.
Specify the alignment of your image. Type align=”middle”> This is the end of the image portion of your tag. [1] X Research source
Add more text. Then, close the tag with
. For example, your entire tag could look like this:
We’re learning about HTML. Our example is complete.
Aligning in a Center Tag
Create a new element and center that element. You can contain the image within that centered element. However, it will create extra spaces around your element.
Add your image tag. Type .
Specify the height and width of the image. Enter height=”200”width=”200”> or another size of your choice. This is the end of your image portion of the tag.
Community Q&A
The align attribute of is not supported in HTML 5. Use CSS instead. For the image to align middle, top, or bottom use the CSS property vertical-align. For the image to align left or right use the CSS property float.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow
The align tribute of HTML is not supported by in HTML5. So you should use CSS instead. So that you can align the middle, top, and sides of an image. To do this use the CSS property vertical-sign, which makes the image align to the left or right use the CSS property float.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow
Use this code. You can either use this method or try putting the image in a container, like div with and style the container to align it’s content to center.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow
CSS Image Centering – How to Center an Image in a Div
Joel Olawanle
When you’re working on the front-end of a web page, you sometimes need to center an image within a div (container).
This can become tricky at times. And based on certain conditions, a particular method may not work at some point, leaving you searching for alternatives.
In this article, you will learn how to center an image in a div with CSS.
How to Center a div using CSS
You center an image in a div in two ways: horizontally and vertically. When you put these two methods together, you will have an entirely centered image:
By default, web content always begins from the top-left corner of the screen and moves from ltr (left to right) – except for certain languages like Arabic, which goes from rtl (right to left).
Let’s start by seeing how to center an image within a div horizontally. Then we’ll see how to center vertically. Finally, we’ll see how you can do both together.
How to Center an Image in a Div Horizontally with Text-align
Suppose you have a div in which you place your image this way:
And apply basic CSS styling so your image is visible:
The text-align method won’t work in all cases, as you typically use it to center text. But when you have your images within a block level container like a div , then this method will work:
This works by adding the text-align property alongside its value of center to the container and not the image itself.
How to Center an Image in a Div Horizontally with Margin-auto
Another method that you can use to horizontally center an image within a div (container) is the margin property with the value of auto .
The element will then take up the specified width , and the remaining space will be split equally between the left and right margins.
You would usually apply this method to the image itself and not the container. But unfortunately, this property alone doesn’t work. You also need to specify the width the image will take first. This lets the margin know the remaining width the container has so that it can be split equally.
Secondly, img is an inline element, and the margin-auto property set does not affect inline-level elements. This means you must first convert it to a block-level element with display property set as block .
How to Center an Image in a Div Horizontally with the Position and Transform Properties
Another method you can use to position an image horizontally is the position property alongside the transform property.
This method can be very tricky, but it works. You must first set the container’s position to relative , then the image to absolute .
Once you do this, you can now move the image to whichever position you wish using either the left , top , bottom , or right properties on the image.
In this case, you only want to move the image to the center horizontally. This means you would move the image via the left to 50% or right to -50%:
But when you check your image, you will notice that the image is still not perfectly placed in the center. This is because it started from the 50% mark, which is the center position.
In this case, you need to use the transform-translateX property to adjust it to get the perfect center horizontally:
How to Center an Image in a Div Horizontally with Display-Flex
CSS flexbox makes it easier for you to design flexible, responsive layout structures without using float or positioning. We can also use this to place an image in the center horizontally of a container using the display property with flex as its value.
But this alone doesn’t work. You also need to define the position where you want your image. This could be center, left or maybe right :
Note: The display: flex property is not supported in older versions of browsers. You can read more here. You’ll also notice that the width and height of the image are defined to ensure the image doesn’t shrink.
Let’s now learn how to center an image in a div vertically. Later we’ll see how to center an image in a div horizontally and vertically together, making it a perfect center.
How to Center an Image in a Div Vertically with Display-Flex
Just like how you were able to center the image horizontally with the display-flex method, you can also do the same vertically.
But this time around, you won’t need to use the justify-content property. Rather you’ll use the align-items property:
For this method to work, the container must have a specified height which you will use to calculate the height and know where the center is located.
How to Center an Image in a Div Vertically with the Position and Transform Properties
Similar to how you used the position and transform properties earlier to place your image in the center horizontally, you can also do the same vertically.
But this time around, you won’t use left or right, . Instead you will use top or bottom alongside translateY rather than translateX :
You have learned how to center an image within a div horizontally and vertically using all possible methods. Let’s now learn how to center both horizontally and vertically.
How to Center an Image in a Div Horizontally and Vertically with Display-Flex
The display-flex property is a combination of how you’d center the image vertically and horizontally.
For the flex method, this means you will use both the justify-content and align-items properties set to center :
How to Center an Image in a Div Horizontally and Vertically with the Position and Transform Properties
This is also very similar, as all you have to do is combine both ways you were able to center vertically and horizontally:
You can also combine the translateX and translateY by using translate(x,y) :
Wrapping Up
In this article, you have learned how to center an image in a div vertically, horizontally, or both.
You will often use the Flexbox method when moving an image to the center because the position method can distort your web page and works very trickily.
You can learn more about the CSS position method here and then more about the flexbox method here.
Как выровнять картинку по центру с помощью CSS
В этой статье рассмотрим, какие есть методы выравнивания картинки по центру блока.
Давайте создадим нашу разметку, с которой будем работать.
Создадим класс .wrap и внутрь его добавим картинку с классом .photo
Теперь перейдем к css. Зададим фиксированную ширину и высоту для блока, а также добавим для него border — чтобы мы видели границы элемента:
А для самой картинки зададим ширину 250px:
Вот так сейчас выглядит наша разметка:
Разметка готова, теперь перейдем к вариантам, как можно выровнять картинку по центру блока.
Первый вариант
Не идеальный. Мы можем добавить классу .wrap свойство text-align:center; и тогда все, что внутри блока будет отцентрировано по горизонтальной оси.
Есть еще вариант, как разместить картинку по центру. Для этого нужно ее перевести в блочный элемент, и с помощью margin: auto; выставить по центру:
Далее мы перейдем к вариантам, которые позволят нам выровнять картинку по центру блока и выровнять ее по вертикали.
Второй вариант
С помощью display: flex мы можем отцентрировать не только по оси x, но и по оси y. Давайте добавим классу .wrap следующие свойства:
Получим следующую картину:
А если пропишем следующий код:
То по горизонтальной оси выровняем по правому краю (свойство justify-content: flex-end), а с помощью align-items: flex-end; выровняем изображение по нижнему краю.
Третий вариант
Если предыдущие два варианта центрировали не только картинку, но и любое содержимое внутри блока .wrap, то следующий вариант будет относиться только к картинке.
Это основные способы, которые позволят вам выровнять картинку по центру блока. Если вы нашли более удобный способ реализовать данную задачу, делитесь в комментариях.
А если остались вопросы, то советую посмотреть видео, где я подробно объясняю и показываю в действии вышеперечисленные способы.