Reputation: 583
I have a container within which i will get contents dynamically. i want all coming contents/div to be centred automatically. i dont want to use margin property.
<div class="linContainer">
<div class="content1"></div>
<div class="content2"></div>
</div>
Upvotes: 3
Views: 5848
Reputation: 29
<div class="align">
Test
</div>
div.align {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color:#ff6a00;
}
Upvotes: 0
Reputation: 1329
The best way to achieve this is to use css flex.
Note: margin has just been used to define space between content blocks, not to center it.
.flex-container {
display: flex;
align-items: center;
justify-content: center;
flex-direction: row;
flex-wrap: wrap;
flex-flow: row wrap;
align-content: flex-end;
}
.linContainer{
background:#aeaeae;
}
.content1, .content2, .content3, .content4{
background:lawngreen;
padding:20px;
margin:10px;
}
<div class="linContainer flex-container">
<div class="content1"></div>
<div class="content2"></div>
<div class="content3"></div>
<div class="content4"></div>
</div>
Upvotes: 0
Reputation: 5564
You can use the following position: absolute
idiom:
.linContainer {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
[class^='content'] {
height: 50px;
width: 50px;
background: cyan;
border: 1px solid black;
}
<div class="linContainer">
<div class="content1"></div>
<div class="content2"></div>
</div>
Or you can use flexbox - display: flex
:
.linContainer {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
[class^='content'] {
height: 50px;
width: 50px;
background: cyan;
border: 1px solid black;
}
<div class="linContainer">
<div class="content1"></div>
<div class="content2"></div>
</div>
Good references on centering with CSS:
Upvotes: 0
Reputation: 8537
To center vertically AND horizontally, you can change the default display
from block
to table-cell
.
Upvotes: 3
Reputation: 50326
Not sure if text-align:center
will serve the purpose.
.linContainer{
width:150px;
height:auto;
text-align:center;
border:1px solid red;
max-height:200px;
}
You can check this jsfiddle
Upvotes: 0
Reputation: 29
.container {
width: 100%;
height: 120px;
background: #ccc;
text-align : center;
}
.centered-content {
display: inline-block;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
Upvotes: 0
Reputation: 5167
try this code
.lincontainer {
display: flex;
justify-content: center;
}
Upvotes: 0
Reputation: 7103
You can do this:
.linContainer {
text-align: center;
}
Note that everything will be centered (including text). Or do you want to center only divs?
Upvotes: 0