PHP前端开发

css中对齐方式有哪些

百变鹏仔 4周前 (09-20) #CSS
文章标签 方式
方式:1、用“text-align:center”样式实现水平居中。2、用“line-height:行高;”样式实现垂直居中。3、用“align-items:center;justify-content:center”样式实现水平垂直居中。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。

css中对齐方式有哪些

一、水平居中

  • 行内元素的水平居中

    立即学习“前端免费学习笔记(深入)”;

如果被设置元素为文本、图片等行内元素时,在父元素中设置text-align:center实现行内元素水平居中,将子元素的display设置为inline-block,使子元素变成行内元素

<div class="parent" style="background-color: gray;">  <div class="child" style="background-color: lightblue;">DEMO</div></div><style>.parent{text-align: center;}    .child{display: inline-block;}</style>
  • 块状元素的水平居中(定宽)

当被设置元素为定宽块级元素时用 text-align:center 就不起作用了。可以通过设置“左右margin”值为“auto”来实现居中的。

<div class="parent" style="background-color: gray;">  <div class="child" style="background-color: lightblue;">DEMO</div>  </div>  <style>.child{            width: 200px;            margin: 0 auto;        }        </style>
  • 块状元素的水平居中(不定定宽)

在实际工作中我们会遇到需要为“不定宽度的块级元素”设置居中,比如网页上的分页导航,因为分页的数量是不确定的,所以我们不能通过设置宽度来限制它的弹性。

可以直接给不定宽的块级元素设置text-align:center来实现,也可以给父元素加text-align:center 来实现居中效果。

当不定宽块级元素的宽度不要占一行时,可以设置display 为 inline 类型或inline-block(设置为 行内元素 显示或行内块元素)

<div class="container">    <ul>        <li><a href="#">1</a></li>        <li><a href="#">2</a></li>        <li><a href="#">3</a></li>    </ul></div><style>.container{text-align:center;background: beige}.container ul{list-style:none;margin:0;padding:0;display:inline-block;}.container li{margin-right:8px;display:inline-block;}</style>

二、垂直居中

和水平居中一样,这里要讲垂直居中,首先设定两个条件即父元素是盒子容器且高度已经设定

子元素是行内元素,高度是由其内容撑开的

这种情况下,需要通过设定父元素的line-height为其高度来使得子元素垂直居中

<div class="wrap line-height">    <span class="span">111111</span></div><style>.wrap{            width:200px ;            height: 300px;            line-height: 300px;            border: 2px solid #ccc;        }.span{            background: red;        }</style>

三、水平垂直居中

在css标签内,将display属性设置为flex,实现flex布局,再将align-items属性设置为center(水平方向居中),justify-content属性设置为center(垂直方向居中)。即可设置为水平垂直居中。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title></head><body>    <div class="mydiv">        <span>测试</span></div><style type="text/css">.mydiv{    width:200px;    height:100px;    border:1px solid black;    display:flex;    align-items:center;    justify-content:center;}</style></body></html>

更多编程相关知识,请访问:编程视频!!