-1

How can i insert image in center of div? this is my html file:

.navbar1 img{
  width: 50px;
  height: 50px;
}
 <div class="navbar1">
    <a href="#end"><img src="down-button.png" alt="به پایین بروید"></a>
</div>

i want to add this image in center of my div.

i add this line to my css file but dont work:

  display: block;
  margin-left: auto;
  margin-right: auto;
Andrew Kovalchuk
  • 897
  • 1
  • 10
  • 29
Tanhaeirad
  • 169
  • 3
  • 13

5 Answers5

3

Here you go

.navbar1 {
  text-align: center
}

.navbar1 img{
  width: 50px;
  height: 50px; 
}
<div class="navbar1">

        <a href="#end"><img src="https://images.unsplash.com/photo-1550942505-8be581ce735d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="به پایین بروید"></a>

</div>
Nilesh Naik
  • 751
  • 3
  • 9
0

There are many ways to achieve this. If you're using margins, i believe it's better to do it in such way, instead of margin: auto:

.navbar1 img{
position: absolute;
width: 50px;
height: 50px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

It also can be done with the usage of "tools" like flexbox.

0

You can achieve this easily by CSS flex property, align-items: center will vertically align the elements and justify-content: center will do this horizontally based on its parent's height and width

.navbar1{
 display:flex;
 width:100%;
 height:100%;
 align-items:center;
 justify-content:center;
}
Rajesh
  • 254
  • 1
  • 6
0

try this, i am using flex property. make sure to use -webkit instead of flex property for browser compatibility.

html

       <div class="navbar1">
        <a href="#end"><img src="down-button.png" alt="به پایین بروید"></a>
       </div>

style

.navbar1{
       display: flex; 
       justify-content: center;
       align-items: center;
}

-webkit(flex):-optional

       display: -webkit-box;     
       display: -moz-box;         
       display: -ms-flexbox;     
       display: -webkit-flex;    
       display: flex; 
       -webkit-justify-content: center;
       -ms-flex-pack: center;
       justify-content: center;
       -webkit-box-align: center;
       -moz-box-align: center;
       -webkit-align-items: center;
       -ms-flex-align: center;
       align-items: center;

thank you.

0

The best way is to use flexbox. Try this code:

.navbar1 {
    display: flex;
     align-items: center;
     justify-content: center;
}
Andrew Kovalchuk
  • 897
  • 1
  • 10
  • 29