CSS居中布局的技巧有哪些

发布时间:2022-03-05 17:00:06 作者:iii
来源:亿速云 阅读:131

本篇内容主要讲解“CSS居中布局的技巧有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“CSS居中布局的技巧有哪些”吧!

水平居中元素:

方式一:CSS3 transform

.parent {

position: relative;

}

.child {

position: absolute;

left: 50%:

transform: translateX(-50%);

}

方式二:flex 布局

.parent {

display: flex;

justify-content: center;

}

适用于子元素为浮动,绝对定位,内联元素,均可水平居中。

居中的元素为常规文档流中的内联元素(display: inline)

常见的内联元素有:span, a, img, input, label 等等

.parent {

text-align: center;

}

居中的元素为常规文档流中的块元素(display: block)

常见的块元素:div, h2~h7, table, p, ul, li 等等

方式一:设置 margin

.parent {

width: 100%;

}

.child {

width: 600px;

height: 50px;

margin: 0 auto;

background: #999;

}

方式二:修改为 inline-block 属性

.parent {

text-align: center;

}

.child {

display: inline-block;

}

.child {

width: 100px;

float: left;

position: relative;

left: 50%;

margin-left: -50px;

}

方式一:

.parent {

position: relative;

}

.child {

position: absolute;

width: 100px;

left: 50%;

margin-left: -50px;

}

方式二:

.parent {

position: relative;

}

.child {

position: absolute;

width: 100px;

left: 0;

right: 0;

margin: 0 auto;

}

垂直居中元素:

方式一:CSS3 transform

.parent {

position: relative;

}

.child {

position: absolute;

top: 50%;

transform: translateY(-50%);

}

方式二:flex 布局

.parent {

display: flex;

align-items: center;

}

适用于子元素为浮动,绝对定位,内联元素,均可垂直居中。

.text {

line-height: 200px;

height: 200px;

}

方式一:

.parent {

position: relative;

}

.child{

position: absolute;

top: 50%;

height: 100px;

margin-top: -50px;

}

方式二:

.parent {

position: relative;

}

.child{

position: absolute;

top: 0;

bottom: 0;

height: 100px;

margin: auto 0;

}

垂直居中元素:

div {

width: 100px;

height: 100px;

margin: auto;

position: fixed;

//absolute is ok

top: 0;

right: 0;

bottom: 0;

left: 0;

}

优点:

不仅可以实现在正中间,还可以在正左方,正右方

元素的宽高支持百分比 % 属性值和 min-/max- 属性

可以封装为一个公共类,可做弹出层

浏览器支持性好

.child {

width: 100px;

height: 100px;

position: absolute;

top: 50%;

left: 50%;

margin-left: -50px;

margin-top: -50px;

}

特点:

良好的跨浏览器特性,兼容 IE6 - IE7

灵活性差,不能自适应,宽高不支持百分比尺寸和 min-/max- 属性

.child {

width: 100px;

height: 100px;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

}

特点:

内容可自适应,可以封装为一个公共类,可做弹出层

可能干扰其他 transform 效果

.parent {

display: flex;

justify-content: center;

align-items: center;

}

这是 CSS 布局未来的趋势。Flexbox 是 CSS3 新增属性,设计初衷是为了解决像垂直居中这样的常见布局问题。

text {

height: 100px;

line-height: 100px;

text-align: center;

}

到此,相信大家对“CSS居中布局的技巧有哪些”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. CSS网页布局的技巧有哪些
  2. 实现CSS垂直居中的技巧有哪些

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

css

上一篇:CSS样式书写规范的方法

下一篇:CSS简写的技巧有哪些

相关阅读

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

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