Search code examples
hyperlinkalignment

Align two side by side divs with a variable-length link in the center of each div


I am trying to have two divs (red boxes) side by side, and within each red box should be a bordered link. One link is on two lines whereas the second link is on one line. The links should lie at the center (horizontally and vertically) of each box, and the two boxes should also be perfectly aligned.

My code is the following. I had to set the links as "display: table-cell;" to keep the two boxes aligned. If you have another solution, i'm listening ^^.

* {
margin: 0;
padding: 0;
}

#marketing-button, #prints-button {
	background-color: red;
	text-align: center;
	width: 10em;
	height: 10em;
	display: inline-block;
}

#marketing-link, #prints-link {
	color: white;
	vertical-align: middle;
	display: table-cell;
	float: none;
	font-size: 1em;
	border: yellow solid 2px;
	text-align: center;
	margin-left: auto;
	margin-right: auto;
	padding: .2em;
}
<body>
		<div id="container">
			<div id="marketing-button">
				<a id="marketing-link" href="#">Digital <br />marketing</a>
			</div>
			<div id="prints-button">
				<a id="prints-link" href="#">Prints</a>
			</div>
		</div>
	</body>

Thanks guys!


Solution

  • Ok, i found the solution. Each link should be set to display as inline-block and should be contained within a div displayed as a table-cell. This allows to center the link vertically.

    The table-cells should themselves be contained within divs displayed as inline-blocks. This allows the red boxes to be aligned and to have a space between them.

    Here is the final code:

    * {
    margin: 0;
    padding: 0;
    }
    
    .container {
    	display: inline-block;
    }
    
    #marketing-button, #prints-button {
    	background-color: red;
    	text-align: center;
    	width: 10em;
    	height: 10em;
    	display: table-cell;
    	vertical-align: middle;
    	margin-right: 20px;
    	
    }
    
    #marketing-link, #prints-link {
    	color: white;
    	display: inline-block;
    	float: none;
    	font-size: 1em;
    	border: yellow solid 2px;
    	text-align: center;
    	padding: .2em;
    }
    <body>
    	
    		<div class="container">
    			<div id="marketing-button">
    				<a id="marketing-link" href="#">Digital <br />marketing</a>
    			</div>
    		</div>
    		<div class="container">
    			<div id="prints-button">
    				<a id="prints-link" href="#">Prints</a>
    			</div>		
    		</div>
    	
    </body>