A div with fixed width and height

Flex layout

HTML: <div class="box"> <div class="box1"></div> </div> CSS:.box{/* method 一 */ width:200px; height:200px; border: 1px solid red; display: flex; justify-content: center; align-items: center; } .box1{ width:100px; height:100px; background-color:yellow; }Copy the code

Absolute positioning + negative margin layout

.box{/* method a */ width:200px; height:200px; border: 1px solid red; position: relative; } .box1{ width:100px; height:100px; position: absolute; left:50%; top:50%; margin-left:-50px; margin-right:-50px; }Copy the code

Absolute position + Transform

.box{/* method a */ width:200px; height:200px; border: 1px solid red; position: relative; } .box1{ width:100px; height:100px; position: absolute; left:50%; top:50%; transform: translate(-50%, -50%); }Copy the code

Left /top/right/bottom

.box{/* method a */ width:200px; height:200px; border: 1px solid red; position: relative; } .box1{ width:100px; height:100px; position: absolute; left:0; top:0; bottom:0; right:0; margin:auto; background-color:yellow; }Copy the code

The grid layout

.box{/* method a */ width:200px; height:200px; border: 1px solid red; display:grid; } .box1{ width:100px; height:100px; position: absolute; left:0; top:0; bottom:0; right:0; margin:auto; background-color:yellow; }Copy the code

A div of variable width and height

Flex layout

HTML: <div class="box"> <div class="box1"> This is a test of div</div> </div> CSS:.box{/* method one */ width:200px; height:200px; border: 1px solid red; display:flex; justify-content: center; align-items: center; } .box1{ background-color:yellow; }Copy the code

Absolute position + Transform

HTML: <div class="box"> <div class="box1"> This is a test of div</div> </div> CSS:.box{/* method one */ width:200px; height:200px; border: 1px solid red; position: relative; } .box1{ position:absolute; left:50%; top:50%; transform: translate(-50%, -50%); background-color:yellow; }Copy the code

Flex variant layout

HTML: <div class="box"> <div class="box1"> This is a test of div</div> </div> CSS:.box{/* method one */ width:200px; height:200px; border: 1px solid red; display:flex; } .box1{ margin:auto; background-color:yellow; }Copy the code

The grid + flex layout

HTML: <div class="box"> <div class="box1"> This is a test of div</div> </div> CSS:.box{/* method one */ width:200px; height:200px; border: 1px solid red; display:grid; } .box1{ justify-self: center; align-self: center; background-color:yellow; }Copy the code

The grid + margin layout

HTML: <div class="box"> <div class="box1"> This is a test of div</div> </div> CSS:.box{/* method one */ width:200px; height:200px; border: 1px solid red; display:grid; } .box1{ margin:auto; background-color:yellow; }Copy the code

If you like it, give it a thumbs up! Thank you