Reputation: 86627
I want to align a div
centered horizontally in the page. The div contains several html content like, images, links, texts etc.
For the sake of it I cannot use display:table
, which would align the div in center. How could I else align the content, without having to give an explicit width
?
Upvotes: 1
Views: 66
Reputation: 3904
Or without using flex, translate or absolute positioning:
#container {
text-align:center;
}
#center {
padding:20px;
display:inline-block;
background:#ccc;
}
<div id="container">
<div id="center">
this is a test
</div>
</div>
Upvotes: 1
Reputation: 22158
You can center horizontally and vertically (as you like) with a translate so easy, and without know the width or the height:
<div class="parent">
<div class="center">
Centered
</div>
</div>
CSS
.parent {
position: relative;
}
.center {
position: absolute;
left:50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
}
To center vertically use translateY()
Snippet:
.parent {
position: relative;
width: 100%;
height: 500px;
border: 1px solid black;
}
.center {
height: 240px;
position: absolute;
left:50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
<div class="parent">
<div class="center">
Centered
</div>
</div>
Upvotes: 0
Reputation: 32255
You will need to use justify-content: center
in flexbox layout. No need of setting a width.
.center {
display: flex;
justify-content: center;
}
<div class="center">
<img src="http://placehold.it/300x300">
<span class="text">Test text</span>
<a href="#">Test link</a>
</div>
Upvotes: 2