我如何将图像置于HTML和HTML中的任何div中心? CSS?

时间:2017-01-08 19:12:43

标签: html css

The Output

我如何将图像置于HTML和HTML中的任何div中心? CSS?

我有一个导航栏,使用图像作为其他页面的链接,导航栏是多个div,每个都有一个图像,而另一个div包含一个单词,我怎样才能将这个img置于div中

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;
}

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>

5 个答案:

答案 0 :(得分:1)

请注意align-self is for elements inside a flexbox container不是您的情况,您可以在text-align: center;上使用img进行尝试。

或者如果您想要完整的flexbox,请将img容器设置为:

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

align-self上的此设置img不需要justify-content,因为它的容器上会有Here is my Demo: http://codepen.io/CRYP3/pen/WRvyxw

答案 1 :(得分:1)

Flexbox 救援:

.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>

答案 2 :(得分:0)

align-self: center;有效,align-self: middle;无效。

但是,您可以通过text-align: center;实现您想要的效果。尽管它是一个图像,你仍然可以使用text-align来居中,因为默认情况下,图像就像文本一样。

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

OR

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

答案 3 :(得分:0)

您需要更改以下图片的CSS: -

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

您可以在此处看到Many Demos -

答案 4 :(得分:-1)

首先,您必须将div的性质更改为table,然后将其对齐到像这样的中心

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