Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How does CSS center the picture? How to center a picture


May 29, 2021 Article blog


Table of contents


As we all know, HTML and CSS are powerful when combined to make ever-changing styles, so do you know how to use CSS to center your pictures? This article tells you

I. display:table-cell

The HTML code is as follows:

<div class="img_wrap">
      <img src="../images/w3cschool.png">
</div>

The CSS code is as follows

.img_wrap{
    width:700px;
    height:350px;
    border:1px dashed #ccc;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    }

Effect map:

 How does CSS center the picture? How to center a picture1

Second, the use of background law

html code:

<div class="img_wrap"></div>

CSS code:

.img_wrap{
    width:700px;
    height:350px;
    border:1px dashed #ccc;
    background: url("../images/w3cschool.png") no-repeat center center;
    }

Effect map:

 How does CSS center the picture? How to center a picture2

Third, line-height

This method uses a p-label outside the picture to center the picture vertically by setting line-height:

HTML code:

<div class="img_wrap">
        <p><img src="../images/ss.png" alt=""></p>
</div>

CSS code:

.img_wrap{
    width:700px;
    height:350px;
    border:1px dashed #ccc;
    text-align: center;
}
.img_wrap p{
     width: 700px;
     height:350px;
     line-height: 350px;
}
.img_wrap p img{
     vertical-align: middle;
}

Effect map:

 How does CSS center the picture? How to center a picture3

These are three detailed ways to center your images using CSS, and you can click on more CSS-related tutorials: CSS Microsys, HTML-CSS Basics