将之前的用到的记录一下。以便不时之需。朋友一直和我讲css 是不简单,到目前为此,css发展已经进化到越来越惊人。其实学好css 不容易,也没有人所说的那样简单。css2- css3 – 进化less,sass,postcss,似乎真是越来越多。那天看了一下less,增加了一些嵌套和变量编程。似乎也不错。
先将一些记录下来。
1.text-align 实现居中效果
这种适合inline的元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.center{
text-align: center;
border: 1px solid red;
}
</style>
<body>
<div class="center">
我的文字居中了
</div>
</body>
</html>
2.margin :0 auto 实现居中效果
使用margin:0 auto;的方式可以实现一些固定的尺寸div的时候 实现居中。当内部子div设置了尺寸宽度后,可以使用对应的处理
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.center{
border: 1px solid red;
padding: 20px 20px;
}
.sub_center{
width: 300px;
height: 150px;
border: 1px solid red;
margin: 0 auto;
text-align: center;
line-height: 150px;
}
</style>
<body>
<div class="center">
<div class="sub_center">我的文字居中了</div>
</div>
</body>
</html>
3.使用position方式处理
使用绝对定位的方式来实现居中效应。transform 在不确定具体尺寸的时候使用。使用transform相对偏移50% 可以解决到在left 和top的时候情况。 使用在IE低版本兼容性 存在问题。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.center{
border: 1px solid red;
padding: 20px 20px;
position: relative;
}
.sub_center{
width: 300px;
height: 150px;
border: 1px solid red;
position: absolute;
left:50%;
top: 50%;
transform: translate(-50%,-50%);
text-align: center;
line-height: 150px;
}
</style>
<body>
<div class="center">
<div class="sub_center">我的文字居中了</div>
</div>
</body>
</html>
4.使用flex的方式
flex 和配合justify-content: center;方式可以实现内部元素实现居中效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.center{
border: 1px solid red;
padding: 20px 20px;
display: flex;
justify-content: center;
}
.sub_center{
width: 300px;
height: 150px;
border: 1px solid red;
text-align: center;
line-height: 150px;
}
</style>
<body>
<div class="center">
<div class="sub_center">我的文字居中了</div>
</div>
</body>
</html>