您的位置:首页 > Web前端 > CSS

css元素水平垂直居中

2019-08-09 15:19 971 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/tinfengyee/article/details/98957690

页面结构

vertical-align: middle;针对行内块元素使用 , 如 input 对齐, img 去掉下边空白,

<body>
<div class="box">
<div class="wrapper">hehe</div>
</div>
</body>

行内元素
父设置

text-align:center;
实现水平居中,元素设置行高
line-height: 500px;
垂直居中.

/* 父元素设置line-height 可以让文本之类的垂直居中 */
<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
text-align: center;
line-height: 500px;
}
.wrapper {
background-color: rebeccapurple;
display: inline;
border:1px solid red;
}
</style>

/* 子元素行高等于父元素高度 */
<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
text-align: center;
}
.wrapper {
line-height: 500px;
background-color: rebeccapurple;
display: inline;
border:1px solid red;
}
</style>

块级元素
1 绝对定位 + transform

<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
position: relative;
}

.wrapper {
position: absolute;
width: 100px;
height: 100px;
background-color: rebeccapurple;
display: block;
border: 1px solid red;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>

2

flex
布局,推荐

<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
display: flex;
justify-content: center;
align-items: center;
}

.wrapper {
width: 100px;
height: 100px;
background-color: rebeccapurple;
display: block;
border: 1px solid red;
}
</style>

3

display: table-cell;

<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
display: table-cell;
text-align: center;	 /* 行内块元素用这个 */
vertical-align: middle;
}

.wrapper {
width: 100px;
height: 100px;
background-color: rebeccapurple;
/* display: block; */
display: inline-block;
/* margin: 0 auto; 块级元素 要同这个 */
border: 1px solid red;
}
</style>

margin:0 auto;
水平居中,要设置宽度

<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
}

.wrapper {
width: 100px;
height: 100px;
background-color: rebeccapurple;
display: block;
border: 1px solid red;
margin: 0 auto;
}
</style>

行内块元素

<style>
.box {
width: 500px;
height: 500px;
background-color: rgb(108, 202, 209);
text-align: center;
line-height: 500px;
}
.wrapper {
width: 100px;
height: 100px;
background-color: rebeccapurple;
display: inline-block;
border:1px solid red;
line-height: 100px; /* 让盒子下来 */
}
</style>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐