box-sizing属性
属性值 | 定义 |
---|---|
content-box | 盒模型以元素内容区为边界,不包含padding、border值 |
border-box | 盒模型以元素边框区为边界,包含padding、border值 |
- 代码演示
<style>
body div:first-of-type {
width: 100px;
height: 100px;
background-color: lightcoral;
border: 2px solid #000;
box-sizing: content-box;
padding: 5px;
}
body div:first-of-type + * {
width: 100px;
height: 100px;
background-color: lightcoral;
border: 2px solid #000;
box-sizing: border-box;
padding: 5px;
}
</style>
</head>
<body>
<div></div>
<div></div>
</body>
图片演示
box-sizing:content-box div元素原始宽、高为100px,增加border、padding后宽高变成114px
box-sizing:border-box div元素原始宽、高为100px,增加border、padding后宽高仍然保持100px
元素居中方式
行内元素及行内块元素居中方式
水平居中 text-algin:center;
<style>
body div:first-of-type {
width: 300px;
height: 300px;
border: 1px solid;
text-align: center;
}
body div:first-of-type + * {
width: 300px;
height: 300px;
border: 1px solid;
text-align: center;
}
</style>
</head>
<body>
<div>行内元素水平居中</div>
<div><img src="https://www.php.cn/static/images/index_php_item3.jpg?1" alt="" /></div>
</body>
图片演示:
垂直居中
1.行内元素垂直居中 行高与高度一致
<style>
body div:first-of-type {
width: 300px;
height: 300px;
line-height: 300px;
border: 1px solid;
text-align: center;
}
</style>
</head>
<body>
<div>行内元素水平居中</div>
</body>
图片演示:
2.行内块元素垂直居中
<style>
body div {
width: 300px;
height: 300px;
border: 1px solid;
position: relative;
}
div img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div><img src="https://www.php.cn/static/images/index_php_item3.jpg?1" alt="" /></div>
</body>
图片演示:
- 块元素居中
1.水平居中 margin:0 auto;
<style>
.cont {
width: 200px;
height: 200px;
border: 1px solid;
}
.top {
width: 50px;
height: 50px;
margin: 0 auto;
background-color: red;
}
</style>
</head>
<body>
<div class="cont">
<div class="top"></div>
</div>
</body>
图片演示:
2.垂直居中
方法一:
<style>
.cont {
width: 200px;
height: 200px;
border: 1px solid;
display: table-cell;
vertical-align: middle;
}
.top {
width: 50px;
height: 50px;
margin: auto;
background-color: red;
}
</style>
</head>
<body>
<div class="cont">
<div class="top"></div>
</div>
</body>
图片演示:
方法二:用行内块元素的浮动定位方式也可以达到相同效果