CSS常见布局与居中

juzhengqian0 2019-06-29

这里,就CSS左右布局,左中右布局,水平与垂直居中,进行讨论。

CSS常用于控制页面布局的定位机制:
普通流、相对定位、绝对定位和固定定位。还可以使用float属性来让元素浮动。

1.左右布局

最常用的就是通过浮动(左浮或右浮)来实现浮动。
float属性允许你将普通流中的元素在它的包含元素内尽可能的向左或向右排列。
你应该设置margin属性来制定浮动元素之间的间距。

不同元素的高度和宽度不同,为防止浮动元素的后一元素自动上浮,可以为父元素赋予clearfix类来清除浮动解决这一问题。

<div class="parent clearfix">
  <div class="descendant1">left</div>
  <div class="descendant2">right</div>
</div>

同时在CSS中关于伪类作出声明:

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

设置左浮动(或右浮动),将两个子元素左右并排实现布局:

.descendant1,
.descendant1 {
  float: left;
  margin-left: 30px;
}

还可以通过绝对定位,通过元素脱离文档流来实现。

<div class="parent">
  <div class="descendant1">left</div>
  <div class="descendant2">right</div>
</div>

.parent {
  position: relative;
}
.descendant1 {
  position: absolute;
  left: 0;
  top: 0;
}
.descendant2 {
  position: absolute;
  left: 60px;
  top: 0;
}

2.左中右布局

我们类比左右布局,在此基础上实现由两个元素变为三个元素的布局。

通过全部左浮(或右浮)实现:

<div class="parent clearfix">
  <div class="descendant1">left</div>
  <div class="descendant2">center</div>
  <div class="descendant3">right</div>
</div>

.descendant1,
.descendant2,
.descendant3 {
  float: left;
  margin-left: 20px;
}

同理,第一个元素左浮,第三个元素右浮;同时设置三个元素为内联元素:

.descendant1 {
  float: left;
  margin-left: 20px;
  display: inline-block;
}
.descendant2 {
  margin-left:20px;
  display: inline-block;
}
.descendant3 {
  float: right;
  margin-right: 260px;
  display: inline-block;
}

通过绝对定位:

<div class="parent">
  <div class="descendant1">left</div>
  <div class="descendant2">center</div>
  <div class="descendant3">right</div>
</div>

.parent {
  position: relative;
}
.descendant1 {
  position: absolute;
  left: 0;
  top: 0;
}
.descendant2 {
  position: absolute;
  left: 60px;
  top: 0;
}
.descendant3 {
  position: absolute;
  left: 120px;
  top: 0;
}

3.水平居中

文字居中:

text-align: center;

如果想让一个元素水平居中,首先确定你已经给元素设定了一个宽度(否则将溢满整个屏幕)。
可以通过设置左右的外边距为auto值来居中(包括图片)。

<body>
  <p class="text">You can go to everywhere.
    <br>If you like.
  </p>
</body>

p.text {
  max-width: 300px;
  text-align: center;
  margin: 0 auto;
}

4.垂直居中

在单行文本或按钮、小图中的文字很使用的方法,即设置行高与元素高度一致即可。

<p class="text">
    button
</p>

p.text {
  height: 60px;
  line-height: 60px;
}

也可以根据实际需要尺寸,为所在元素设置上下的padding来实现居中:

p.text {
  padding: 15px 0;
  line-height: 60px;
}




Written by:EdenSheng
Email:singlesaulwork@gmail.com

相关推荐

覆雪蓝枫 / 0评论 2019-06-27