CSS controls the horizontal and vertical centering of child elements (two)

It is different from (1), look carefullyThe difference is in .time-date

First look at the final rendering

Insert picture description here

Description: The header is the outer container, and the picture is the background.
Requirements:
(1) Set time-data, centered in the container, that is, centered in the background image.
(2) Set two text data and time in the center. The time-data is also centered.

 <view class="header">
    <image src="../../static/recommendSong/recommendSong.jpg"></image>
    <view class="time-date">
      <text class="date">{
   
   {date}}</text>
      <text class="time">{
   
   {time}}</text>
    </view>
  </view>
.header{
    
    
  position: relative;
  height: 300rpx;
}
.header image{
    
    
  height: 300rpx;
  width: 100%;
}
/* 设置日期剧中显示 */
.time-date{
    
    
  /* 设置在父元素居中 */
  position: absolute;
  height: 170rpx;
  width: 400rpx;
  border: red solid 1rpx;
  top:50%;
  left:50%;
  margin-top: -85rpx;
  margin-left: -200rpx;
  /* 设置里面内容居中 */
  display: flex;
  flex-direction: column;
  align-items: center;
}
.time-date text{
    
    
  height: 85rpx;
  line-height: 85rpx;
}

CSS code description:
1. First set the time-date in the center of the container, turn on the relative positioning of the parent element, turn on the absolute positioning of the child element, set the width and height of the child element, and set the upper and left offsets to percent of the width of the parent element Fifty is the effect of the picture below.
Insert picture description here
The offset is determined by the upper left corner of the element, so when the box is pulled up by half of its height, the width is generally centered when the box is pulled to the left.
Insert picture description here

2. Next, set the text to be centered in the time-date. First, there are two lines of text. The height must be divided equally, and then each is centered. We use flex layout to modify the direction of the flex box to align the columns, and then use the align-item property to set the horizontal center of the content. Finally, set the line height and height of the text separately, the purpose is to make the text vertically centered.

If you make a mistake, please criticize and correct me, and I welcome your comments!

Guess you like

Origin blog.csdn.net/qq_44606064/article/details/114529763