简体   繁体   中英

How can i center image in any div in HTML & CSS?

输出

How can i center image in any div in HTML & CSS ?

I have a nav bar that uses images as links for other pages, the nav bar is multiple divs each has an image and anther div contains a words, how can I center this img in the div

The CSS:

#Nav
{           
  height:  150px; 
  margin-top: 50px;
}
#Nav ul
{
  list-style-type: none;
  padding: 50px;
  padding-top: 0px;
  width: 100%;
}
#Nav li
{
 float: left;
 font-size: 12px; 
 font-weight: bold; 
 letter-spacing: 0; 
 margin: 30px;
}
#Nav a
{
 display: inline-block;
 padding: 5px;  
 width: 70px;
 height: 100px;
 color: black;
 text-decoration: none;
}
#Nav a:hover 
{
 border: 2px solid #ddd;
 border-radius: 4px;
 box-shadow: 0 0 2px 1px rgba (0, 140, 186, 0.5);
}
#img img 
{
 align-self: middle; 
 width: 50px;
 height: 50px;
}
#desc 
{
 margin-top: 15px;
 text-align: center;
}

The html:

<li> <a target="_blank" href="#"> 

          <div id="img"> <img src="C:/Users/hp1/Desktop/Website/Pictures/Accessories.jpg" alt="Accessories">

            <div id="desc"> Accessories </div> 

          </div> 

 </a> </li>

You need to change your CSS for image like below:-

#img img 
{
 display: block;
 margin: 0 auto;
}

You can see Many Demos Here-

Note that align-self is for elements inside a flexbox container which is not your case, you can try with text-align: center; on img .

Or if you wish to go full flexbox, set the img container to:

.containerClass {
    display: flex;
    flex-flow: column wrap;
    justify-content: center;
}

With this setup align-self on the img is not need since justify-content on it's container will do.

Flexbox to the rescue:

 .parent { width:200px; height:200px; border:2px solid #000; display: flex; /* Make it flex */ flex-direction: column; /* wrap children elements to columns */ align-items: center; /* Center children horizontally */ justify-content: center; /* Center children vertically */ }
 <div class="parent "> <img src="http://placehold.it/100x100/cf5"> <p>Green-ish</p> </div> <div class="parent "> <img src="http://placehold.it/100x100/5fc"> <p>Blue-ish</p> </div>

align-self: center; is valid, align-self: middle; is not valid.

However, you can probably achieve what you're wanting with text-align: center; . Despite it being an image, you can still center using text-align as images are, by default, inline elements just like text.

#img img 
{
 align-self: center; 
 width: 50px;
 height: 50px;
}

OR

#img img 
{
 text-align: center; 
 width: 50px;
 height: 50px;
}

First you have to change the nature of div to table then make its align to center like this

 #img img 
{
display:table;
 align: center; 
 width: 50px;
 height: 50px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM