How to center div in html
This article mainly introduces the relevant knowledge of how to make div center in html, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this html article on how to make div center. Let's take a look at it.
Margin method
You can center the div by margin, and divide the width of the child element by 2 (in this case: (400,100) / 2=150px) by setting the value of the margin-left as the parent element, and divide the value of margin-top by the height of the parent element minus the height of the child element by dividing by 2 (in this case: (300,100) / 2=100px)
Example:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
.box {
Width:400px
Height: 300px
Border: 1px solid # ccc
}
.box1 {
Width:100px
Height: 100px
Background-color: pink
Margin-left: 150px
Margin-top:100px
}
Effect picture:
Position method
We can make the div center vertically by positioning. We can set the absolute positioning of the child element, and set the top and left values to 50%. But we should note that the edge value should also be set when positioning is in use, where the values of margin-left and margin-right are both negative, and the value is half the width and height of the child element.
Example:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
.box {
Width:400px
Height: 300px
Border: 1px solid # ccc
Position: relative
}
.box1 {
Width:100px
Height: 100px
Background-color: pink
Position: absolute
Top: 50%
Left: 50%
Margin:-50px 0 0-50px
}
Effect picture:
This is the end of the article on "how to center div in html". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to make div center in html". If you want to learn more knowledge, you are welcome to follow the industry information channel.