I sometimes build my html website and need to add few things after i finish which i didnt expect to put at the beginning for example like an image between the lines so i just opem img tag and put the image without putting it in a div or span. so the problem is i dont know how to center it then. Is there anyway to center an item that doset have a parent container? here is an example code
<html><img src="img.jpg" alt="img"></html> <style>text-align: center;</style>
the problem with this code is that it dosent center anything I also tried to use literly all properties that can center like "justify-content: center; or align-items: center;" but the img dosent move at all and I only can move it by using padding or margin which is not the best way to do.
Does anyone have an Idea of how i can center an item that dosent have an parent Container like div or this dosent work in html/css?
CodePudding user response:
If you want to fix your code so that it would work, be sure to add html
within the style
section of your code. Like this:
<html><img src="img.jpg" alt="img"></html> <style>html { text-align: center; }</style>
But that will make everything centered. If you want only the image to be centered, do this:
<html><img src="img.jpg" id="myimage" alt="img"></html> <style>#myimage { text-align: center; }</style>
OR
There's an alternate solution (which someone else already posted here), about using display:block
and margin:0 auto
-- that's also doable.
There are 2 ways that this could work for you:
Option 1:
<html><img src="img.jpg" style="display:block; margin:0 auto;" alt="you should probably leave alt blank if the image is decorative, otherwise actually describe what it is"></html> <style>html { text-align: center; }</style>
Option 2:
<html><img src="img.jpg" id="#myimage" alt="img"></html> <style>#myimage{ display:block;margin: 0 auto; }</style>
Ultimately, it comes down to actually learning CSS and how stylesheets work. You might want to do some learning about that, find some "learn CSS" videos on youtube and websites -- this is sorta core stuff, so if you don't understand it yet, research the basics a bit more.
CodePudding user response:
For an image specifically, you could use display: block
and margin:0 auto
like: <img src="img.jpg" style="display:block; margin:0 auto;" alt="img">
Additional Reading: https://www.freecodecamp.org/news/how-to-center-an-image-in-css/
CodePudding user response:
You can define the display property as "flex".
<html><img src="img.jpg" ></html>
.Myimg
{
display: flex;
justify-content: center;
}