简体   繁体   中英

Align Text in Middle of Grid box

How do I vertically align text in the middle of a box? This does not center text in vertical middle. see red arrow below.

 .grid-container { display: grid; grid-template-columns: 140px 140px; grid-template-rows: 140px; align-items: stretch; } img { width: 100%; height: auto; } .test { text-align:center; vertical-align:center; }
 <div class="grid-container" id="gridid42f08d611e2346748fbe47264fd732e0"> <img class="imgcard mCS_img_loaded" id="imgid42f08d611e2346748fbe47264fd732e00" src="https://www.woodlandtrust.org.uk/media/100078482/Sycamore01.jpg?cb=-11897985&amp;preset=gallery-tab-main-image"> <div class="test"> test </div> </div>

在此处输入图片说明

test

How about align-self: center; on the child? (see also on MDN )

That is:

.test {
  align-self: center;
}

Here's your example, but with that extra property:

 .grid-container { display: grid; grid-template-columns: 140px 140px; grid-template-rows: 140px; align-items: stretch; } img { width: 100%; height: auto; } .test { text-align: center; align-self: center; }
 <div class="grid-container" id="gridid42f08d611e2346748fbe47264fd732e0"> <img class="imgcard mCS_img_loaded" id="imgid42f08d611e2346748fbe47264fd732e00" src="https://www.woodlandtrust.org.uk/media/100078482/Sycamore01.jpg?cb=-11897985&amp;preset=gallery-tab-main-image"> <div class="test"> test </div> </div>

As a sidenote, in your question you have vertical-align: center , which is incorrect; the vertical-align property takes middle instead (for whatever bizarre reason)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM