Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

html - Vertical Align Methods

What are the best methods to vertically-align something relative to it's elements dimensions. As of right now, I'm only aware of vertical-align:middle; working well inside of a <tr>.

Are there any other methodologies that I'm overlooking that can work to procedurally accomplish this goal?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here are 3 very good techniques for vertically centering a child within a container - even when you don't know the height of the child element. The first 2 come from this CSS-tricks article

Markup (for all methods):

<div class="block">    
    <div class="centered">
        Some text
    </div>    
</div>

Solution #1: CSS tables method (FIDDLE)

CSS:

/* This parent can be any width and height */
.block {
  display: table;
   width: 100%;
   background: orange;
   height: 300px;
}


.centered {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
   background: pink;
}

Solution #2: Pseudo ('Ghost') element method (FIDDLE)

CSS:

/* This parent can be any width and height */
.block {
  text-align: center;
  background: orange;
  height: 300px;

}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
    background: pink;
}

Solution #3: Flexbox (FIDDLE)

(Relevant) CSS:

.block {
   background: orange;
   height: 300px;
   display: flex;
   align-items: center;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...