实现水平居中,垂直居中,垂直水平居中,水平两端对齐和垂直两端对齐的几种方法

水平居中

方法一:使用text-align属性

<div style="text-align: center;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

方法二:使用flexbox布局

<div style="display: flex; justify-content: center;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

垂直居中

方法一:使用line-height属性

<div style="height: 200px; line-height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

方法二:使用table-cell和vertical-align属性

<div style="display: table-cell; vertical-align: middle; height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

方法三:使用flexbox布局

<div style="display: flex; align-items: center; height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

垂直水平居中

方法一:使用text-align和line-height属性

<div style="text-align: center; height: 200px; line-height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

方法二:使用table和table-cell布局

<div style="display: table; height: 200px; width: 100%; text-align: center;">
  <div style="display: table-cell; vertical-align: middle;">
    <p>这是一段文字</p>
    <img src="image.jpg">
  </div>
</div>

方法三:使用flexbox布局

<div style="display: flex; align-items: center; justify-content: center; height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

水平两端对齐

方法一:使用text-align属性

<div style="text-align: justify;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

方法二:使用flexbox布局

<div style="display: flex; justify-content: space-between;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

垂直两端对齐

方法一:使用line-height属性

<div style="height: 200px; line-height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

方法二:使用table和vertical-align属性

<div style="display: table; height: 200px;">
  <div style="display: table-cell; vertical-align: top;">
    <p>这是一段文字</p>
    <img src="image.jpg">
  </div>
  <div style="display: table-cell; vertical-align: bottom;">
    <p>这是一段文字</p>
    <img src="image.jpg">
  </div>
</div>

方法三:使用flexbox布局

<div style="display: flex; align-items: flex-start; justify-content: space-between; height: 200px;">
  <p>这是一段文字</p>
  <img src="image.jpg">
  <p>这是一段文字</p>
  <img src="image.jpg">
</div>

猜你喜欢

转载自blog.csdn.net/weixin_56006480/article/details/130840531