怎么用纯css多种方法实现div中单行文字、多行文字及嵌套div垂直水平居中

发布时间:2021-07-26 21:53:20 作者:chen
来源:亿速云 阅读:116

本篇内容主要讲解“怎么用纯css多种方法实现div中单行文字、多行文字及嵌套div垂直水平居中”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用纯css多种方法实现div中单行文字、多行文字及嵌套div垂直水平居中”吧!

学习过程中经常遇到要居中的问题,水平居中问题比较好解决,而垂直居中问题因为vertical-align经常失效,所以不容易实现,今天将自己总结的一些方法归纳于这边。

1.div中单行文字垂直水平居中。条件:外层div高度已经给定。代码如下:

代码如下:


<style type="text/css">
.div3{
border:1px solid red;
text-align:center;
height:200px;
line-height:200px;
width:300px;
overflow:hidden;
}
</style>
<div class="div3">


2.div中多行文字垂直水平居中。条件:无。代码如下:

代码如下:


<style type="text/css">
.div4{
border:1px solid red;
width:400px;
padding-bottom:20px;
padding-top:20px;
text-align:center;
}
</style>
<div class="div4">
div中多行文字垂直水平居中

div中多行文字垂直水平居中

div中多行文字垂直水平居
</div>


3.div中嵌套div,使得中间div垂直水平居中。条件:无。应用table模拟法。代码如下:

代码如下:


<style type="text/css">
.div1{
border:1px solid red;
display:table-cell; /* 模拟表格法*/
vertical-align:middle;
text-align:center;
height:200px;
width:200px;
}
.div2{
border:1px solid red;
margin:auto;
height:100px;
width:100px;
}
</style>
<div class="div1">
<div class="div2"></div>
</div>


4.div中嵌套div,使得中间div垂直水平居中。条件:外层div和内层div的高度,宽度都已经限定。通过设定margin来使得div居中。代码如下:

代码如下:


<style type="text/css">
.div5{
border:1px solid red;
height:200px;
width:200px;
}
.div6{
border:1px solid red;
height:100px;
width:100px;
margin:50px 50px auto auto;
}
</style>
<div class="div5">
<div class="div6"></div>
</div>


5.div中嵌套div,使得中间div垂直水平居中。条件:外层div高度,宽度不限定,内部div高度,宽度已知,且内外层div的position都必须为absolute。通过设定top,left,margin来使得div居中。代码如下:

代码如下:


<style type="text/css">
.div7{
position:absolute;
border:1px solid red;
height:50%;
width:50%;
}
.div8{
border:1px solid red;
height:100px;
width:100px;
position:absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
</style>
<div class="div7">
<div class="div8">aa</div>
</div>

到此,相信大家对“怎么用纯css多种方法实现div中单行文字、多行文字及嵌套div垂直水平居中”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. div文字如何实现垂直居中
  2. Div实现水平或垂直居中的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css

上一篇:jquery的ajax同步和异步的原理及用法

下一篇:php检测文件编码的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》