Html img not centering

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,161 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

Image titled Center an Image in HTML Step 1

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.

Читайте также:  Html тег для верстки

Image titled Center an Image in HTML Step 2

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.

Image titled Center an Image in HTML Step 3

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.

Image titled Center an Image in HTML Step 4

Specify the alignment of your image. Type align=”middle”> This is the end of the image portion of your tag. [1] X Research source

Image titled Center an Image in HTML Step 5

”dancing

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

Image titled Center an Image in HTML Step 6

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.

Image titled Center an Image in HTML Step 7

Image titled Center an Image in HTML Step 8

”dancing

Add your image tag. Type .

Image titled Center an Image in HTML Step 9

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.

Image titled Center an Image in HTML Step 10

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

Источник

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.

Источник

Выравнивание картинки по центру 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, где вы найдете много интересных видео по разработке сайтов, обзору полезных плагинов и скриптов.

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

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

Источник

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