Center Text Vertically Within

后端 未结 7 2015
孤独总比滥情好
孤独总比滥情好 2020-12-05 16:57

I have a

element with a fixed height, and I\'d like to center some text vertically within that element.

I\'ve been trying to follow the inst

相关标签:
7条回答
  • 2020-12-05 17:51

    As shown below you can easily just set the parent of a text element to position: relative, and the text element itself to position: absolute; Then use direction properties to move around the text inside the parent. See examples below...

    <!--Good and responsive ways to center text vertically inside block elements-->
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Centered Text&reg;</title>
    <style type="text/css">
    @charset "UTF-8";
    * {
    	margin: 0;
    	padding: 0;
    }
    
    body {
    	font-family: Helvetica;
    }
    
    #wrapper {
    	width: 100%;
    	height: auto;
    }
    
    #wrapper > div {
    	margin: 40px auto;
    	overflow: hidden;
      	position: relative;
      	height: 100px;
      	width: 50%;
    }
    
    p {
    	position: absolute;
    	word-wrap: break-word;
    	text-align: center;
    	color: white;
    	background-color: rgba(0,0,0,0.5);
    }
    
    #parent1 {
      background-color: orange;
    }
    
    #parent1 p {
      	top: 10px;
      	bottom: 10px;
      	left: 10px;
      	right: 10px;
      	height: auto;
      	width: auto;
      	padding-top: 30px; /* Parent1's height * 0.5 = parent1 p's padding-top (Adjust to make look more centered) */
    }
    
    #parent2 {
    	background-color: skyblue;
    
    }
    
    #parent2 p {
    	left: 50%;
    	top: 50%;
    	padding: 10px;
    	transform: translate(-50%, -50%);
    }
    
    #parent3 {
    	background-color: hotpink;
    }
    
    #parent3 p {
    	top: 50%;
    	left: 0;
    	transform: translateY(-50%);
    	width: 100%;
    }
    </style>
    </head>
    <body>
    <div id="wrapper">
    	<div id="parent1">
    		<p>Center Method 1</p>
    	</div>
    	<div id="parent2">
    		<p>Center Method 2</p>
    	</div>
    	<div id="parent3">
    		<p>Center Method 3</p>
    	</div>
    </div>
    </body>
    </html>
    I hope this helps!

    0 讨论(0)
提交回复
热议问题