CSSボックスモデルのセンタリング方法

方法1:

マージンを使用します。

<!DOCTYPE html>
<html>    
<head>        
<meta charset="UTF-8">        
<title>demo</title>    
</head>    
<body>        
<style type="text/css">        
    
.div1{ 
width: 100px;
height: 100px; 
border: 1px solid #000000;
}             
.div2{
width:40px ; 
height: 40px; 
background-color: green;
}            
.div22{                
margin-left: 30px;
margin-top: 30px; 
}        
</style>        
<div class="div1">            
<div class="div2 div22">            
</div>        
</div>    
</body>
</html>

方法2

cssのposition属性を使用します。

<!DOCTYPE html>
<html>    
<head>        
<meta charset="UTF-8">        
<title>demo</title>    
</head>   
<body>        
<style type="text/css">

.div1{  
width: 100px; 
height: 100px; 
border: 1px solid #000000;
}             
.div2{ 
width:40px ; 
height: 40px; 
background-color: green;
}             
.div11{                
position: relative;            
}            
.div22{                
position: absolute;
top:50%;
left: 50%;
margin-top: -20px;
margin-left: -20px;            
}        
</style>         
<div class="div1 div11">            
<div class="div2 div22">             
</div>        
</div>     
</body>
</html>

###メソッド
3css3 table-cell、vertical-align:middle;の新しいプロパティを使用します。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{  
width: 100px;
height: 100px; 
border: 1px solid #000000;
} 
.div2{  
width:40px ; 
height: 40px; 
background-color: green;
}
.div11{
display: table-cell;
vertical-align: middle;
}
.div22{
margin: auto;
}
</style>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>

###方法4
フレックスボックスレイアウト
使用して、親要素で直接フレックスボックスレイアウト使用ます

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
<style type="text/css">
.div1 {
width: 100px;
height: 100px;
border: 1px solid #000000;
}
.div2 {
height: 40px;
width: 40px;
background-color: green;
}
.div11 {
display: flex;
/*!*flex-direction: column;*!可写可不写*/
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>

おすすめ

転載: blog.csdn.net/QIANDXX/article/details/112365240