CSS-实现居中

1次阅读

共计 2408 个字符,预计需要花费 7 分钟才能阅读完成。

程度居中

程度居中是咱们在开发的过程中,遇见的十分十分常见的布局,上面???? 我就简略来说一说常见的办法

  1. margin: auto
  2. text-align
  3. flex
  4. position 定位
margin: auto

最简略实现 程度居中 的形式,指标元素必须要有宽度才能够,留神,此办法只对 块级元素 (block) 无效

<style>
    .box {background: #ddd;} 
    .target {width: 200px; height: 100px; background: red; margin: auto;}
</style>
<div class="box">
    <div class="target"></div> 
</div>
text-align

能够实现块级元素外部的行内元素程度居中,留神,此办法只对 行内元素 (inline)、行内块(inline-block)、行内表(inline-table)、inline-flex 元素 程度居中都无效
当有多个行内元素相邻时,也能失效

<style>
    .box {text-align: center; background: #ddd;}
    .target {display: inline-block; width: 50px; height: 50px; background: red;}
<style>
<div class\="box">
    <span class\="target"></span>
</div>
flex

利用弹性布局 flex,通过 justify-content 设置弹性盒子元素在主轴 (默认横轴) 方向上的对齐形式

<style>
  .box {display: flex; justify-content: center; background: #ddd;}
  .target {width: 50px; height: 50px; background: red;}
</style>

<div class="box">
  <span class="target"></span>
</div>
position 定位

看下方代码,能够很清晰的看出,首先父元素要加一行 position: relative,其次必须晓得指标元素的宽度,如果不晓得就必须应用 js 动静的去计算

<style>
  .box {position: relative;}
  .target {position: absolute; left: 50%; margin-left: -1/ 2 宽度}
</style>

<div class="box">
  <div class="target"></div>
</div

垂直居中

程度居中是咱们在开发的过程中,遇见的十分十分常见的布局,上面???? 我就简略来说一说常见的办法

  1. line-height
  2. vertical-align
  3. flex
  4. table-cell
  5. position 定位
line-height

此办法一般而言,是是用于文本垂直居中的,对行内元素,块级元素有效

<style>
  .box {height: 100px; line-height: 100px; background: #ddd;}
  .target {width: 30px; height: 30px; background: red;}
</style>

<div class="box">
  <div class="target"></div>
</div
flex

利用弹性布局 flex,通过 align-items 设置弹性盒子元素在纵轴方向上的对齐形式

<style>
  .box {display: flex; height: 100px; align-items: center; background: #ddd;}
  .target {width: 50px; height: 50px; background: red;}
</style>

<div class="box">
  <span class="target"></span>
</div>
vertical-align

vertical-align 该属性定义行内元素的基线绝对于该元素所在行的基线的垂直对齐

  1. 须要配合伪元素一起应用(留神,要居中的指标元素必须是 inline-block,且伪元素的高度必须为 100%
  2. 配合 display: table-cell 一起应用,次要是要设置父元素的 vertical-aligntable-cell
<style>
  .box {height: 100px; background: #ddd;}
  .box::after {content: ""; display: inline-block; vertical-align: middle; height: 100%;}
  .target {display: inline-block; width: 50px; height: 50px; background: red; vertical-align: middle;}
</style>

<style>
  .box {height: 100px; background: #ddd; display: table-cell; vertical-align: middle;}
  .target {display: inline-block; width: 50px; height: 50px; background: red;}
</style>

<div class="box">
  <span class="target"></span>
</div>
table-cell

vertical-align

position 定位

看下方代码,能够很清晰的看出,首先父元素要加一行 position: relative,其次必须晓得指标元素的高度,如果不晓得就必须应用 js 动静的去计算

<style>
  .box {position: relative;}
  .target {position: absolute; top: 50%; margin-top: -1/ 2 宽度}
</style>

<div class="box">
  <div class="target"></div>
</div
正文完
 0