关键代码:
父类text-align: center;
子类display: inline-block;
讲解:
text-align: center;
是对文本内容进行居中。
当元素是inline-block
的时候其实是同时具备内联元素和块元素的的特征。所以text-align就会生效。
注意:display:inline
内联元素设置宽高是无效的。所以看不到这个盒子,但是里面的文字是可以看到的同时也具备了居中效果。
示例:
<style>
.parent {
width: 100%;
height: 200px;
background-color: rgb(156, 114, 59);
text-align: center;
}
.son {
width: 200px;
height: 200px;
display: inline-block;
background-color: bisque;
}
</style>
</head>
<body>
<div class="parent">
<div class="son">哈哈</div>
</div>
<body>
优缺点分析
text-align
属性针对子元素的行内元素也生效,如果对子元素的行内元素有其他位置的变更,需要重新对子元素设置text-align
元素重新赋值。关键代码:
display: block;
margin: auto;
注意:display
属性值可以为table
或者block
题外知识:
margin属性:外边距
一个值: 表示上右下左的外边距相同
两个值: 第一个表示上下外边距 第二个表示左右外边距
三个值: 第一个表示上边距 第二个表示左右外边距 第三个表示下外边距
四个值: 分别表示上右下左的边距
示例:
<style>
.parent {
width: 100%;
height: 200px;
background-color: rgb(156, 114, 59);
}
.son {
width: 200px;
height: 200px;
background-color: bisque;
/* display: table; */
display: block;
margin: auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="son">哈哈</div>
</div>
</body>
优缺点分析
关键代码:
父类:position: relative;
子类:
position: absolute;
left: 50%;
transform: translateX(-50%);
注意:
示例:
<style>
.parent {
width: 100%;
height: 200px;
background-color: rgb(156, 114, 59);
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: bisque;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="son">哈哈</div>
</div>
</body>
优缺点分析