我爱编程

CSS布局&元素居中&媒体查询

2018-04-10  本文已影响0人  Ru_sunny

什么是布局

现有的样式不能满足人们的需求,人们需要更加具体的分区,例如:导航栏,内容,广告栏等等。

单列布局

image

实现方式:固定的宽度和整体居中

width:500px;
margin: 0 auto;

通栏就是从新创建一个div,将头部或底部包裹在里面,添加背景色,设置合适的高度

双列布局

image

实现方式:一侧固定宽度,一侧自适应宽度

<style>
    .a{
        width: 200px;
        height: 400px;
        background: red;
        float: left;
    }
    .b{
        height: 500px;
        margin-left: 210px;
        background: blue;
    }
</style>
  <div class="a"></div>
  <div class="b"></div>

三列布局

实现方式:左右两侧固定宽度,中间自适应宽度

<style>
    .a{
        width: 200px;
        height: 400px;
        background: red;
        float: left;
    }
    .b{
        height: 400px;
        width: 200px;
        background: blue;
        float: right;
    }
    .c{
        height: 500px;
        background: pink;
        margin-left: 210px;
        margin-right: 210px;
    }
    </style>
    <div class="a"></div>
    <div class="b"></div>
    <div class="c"></div>

元素居中

水平居中

行内元素居中

text-align:center;

块级元素居中

margin: 0 auto;
垂直居中

可以用padding上下相等

padding-top:10px;
padding-bottom:10px;

用绝对定位实现居中

width:200px;
height:300px;
position:absolute;
left:50%;
top:50%;
margin-top:150px;
margin-left:100px;

这种方法需要设置盒子的宽高,margin-top和margin-left分别是宽高的一半
也有一种不需要设置宽高的方法,在css3中有一种新属性是transform:translate(x,y)来实现居中

position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);

用vertical-align:middle实现居中
vertical-align 属性设置元素的垂直对齐方式,但是它的定义是行内元素的基线相对于该元素所在行的基线的垂直对齐


当我们设置只设置a vertical-align:middle时

所以当我们想让图片也垂直居中时就要让图片也设置vertical-align:middle


image
当我们明白原理之后,会想如何让文字不占位置呢,可以像下面这样运用伪元素
<div class=“box”>
<img src=“http://.......”>
</div>
<style>
.box{
  width: 300px;
  height: 200px;
  border: 1px solid ;
  text-align: center;
}
.box:before{
  content:'';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.box img{
  vertical-align: middle;
  background: blue;
}
</style>

用display:table-cell来实现居中

<div class=“box”>
<img src=“http://.......”>
</div>
<style>
.box{
  width: 300px;
  height: 200px;
  border: 1px solid ;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
</style>

用display:flex来实现居中

<div class=“box”>
<img src=“http://.......”>
</div>
<style>
.box {
  width: 100vw;
  height: 100vh;  /* 设置宽高以显示居中效果 */
  display: flex;  /* 弹性布局 */
  align-items: center;  /* 垂直居中 */
  justify-content: center;  /* 水平居中 */
}
body{
  margin: 0;
}
</style>

媒体查询

一个媒体查询由一个可选的媒体类型和零个或多个使用媒体功能的限制了样式表范围的表达式组成,例如宽度、高度和颜色。媒体查询,添加自CSS3,允许内容的呈现针对一个特定范围的输出设备而进行裁剪,而不必改变内容本身。

@media screen and (max-width:900px){
  .container{
    background: red;
  }
}

当媒体乐行匹配且表达式为真时,对应的style就起其作用,除非使用not或者only操作符,否则媒体类型不是必须的,默认代表所有媒体类型

更多了解,请点击https://developer.mozilla.org/zhCN/docs/Web/Guide/CSS/Media_queries (中文版)
https://developer.mozilla.org/en-US/docs/Web/CSS/@media (英文版)

上一篇 下一篇

猜你喜欢

热点阅读