美文网首页
CSS定位与布局

CSS定位与布局

作者: 大厂offer | 来源:发表于2019-01-06 11:05 被阅读3次

1、定位

CSS position

relative
(1) 相对定位会按照元素的原始位置对该元素进行移动。
(2) 元素仍然保持其未定位前的形状,它原本所占的空间仍保留。

{
position:relative;
left:-20px
}
这个标题相对于其正常位置向左移动20px

absolute
(1) 通过绝对定位,元素可以放置到页面上的任何位置。
(2) 设置为绝对定位的元素框从文档流完全删除,并相对于其包含块定位
(3) 元素原先在正常文档流中所占的空间会关闭,就好像该元素原来不存在一样。
(4) 元素定位后生成一个块级框,而不论原来它在正常流中生成何种类型的框。
(5) 绝对定位的元素的位置相对于最近的已定位祖先元素,如果元素没有已定位的祖先元素,那么它的位置相对于最初的包含块。

{
position:absolute;
left:100px;
top:150px
}
这个标题距离页面左侧 100px,距离页面顶部 150px

一个综合的例子

.container {
  position: relative;
}
nav {
  position: absolute;
  left: 0px;
  width: 200px;
}
section {
  /* position is static by default */
  margin-left: 200px;
}
footer {
  position: fixed;
  bottom: 0;
  left: 0;
  height: 70px;
  background-color: white;
  width: 100%;
}
body {
  margin-bottom: 120px;
}
一个综合的例子

CSS 浮动

  • 浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。
  • 由于浮动框不在文档的普通流中,所以文档的普通流中的块框表现得就像浮动框不存在一样。

inline-block:

用来平铺div,构建网格,且不用清除浮动

.box2 {
  display: inline-block;
  width: 200px;
  height: 100px;
  margin: 1em;
}

column

可用于实现文字的多列布局

.three-column {
  padding: 1em;
  -moz-column-count: 3;
  -moz-column-gap: 1em;
  -webkit-column-count: 3;
  -webkit-column-gap: 1em;
  column-count: 3;
  column-gap: 1em;
}

2.布局

水平居中

当子元素为:

  • 行内元素:对父元素设置text-align:center;
  • 定宽块状元素: 设置左右margin值为auto;
  • 不定宽块状元素: 设置子元素为display:inline,然后在父元素上设置text-align:center;

通用方案: flex布局,对父元素设置display:flex;justify-content:center;

垂直居中
  • 父元素一定,子元素为单行内联文本:设置父元素的height等于行高line-height
  • 父元素一定,子元素为多行内联文本:设置父元素的display:table-cell或inline-block,再设置vertical-align:middle;
  • 块状元素:设置子元素position:absolute 并设置top、bottom为0,父元素要设置定位为static以外的值,margin:auto;

通用方案: flex布局,给父元素设置{display:flex; align-items:center;}。

相关文章

网友评论

      本文标题:CSS定位与布局

      本文链接:https://www.haomeiwen.com/subject/ohdjmftx.html