EN
CSS - center absolutely positioned element inside div container?
1 answers
0 points
How can I center an absolutely positioned element in a div?
I've tried using left: 50%
but it doesn't work:
xxxxxxxxxx
1
.container {
2
height: 100px;
3
border: 1px solid lightgray;
4
}
5
6
.element {
7
position: absolute;
8
left: 50%; /* doesn't work */
9
}
How can I achieve this effect when the width
is responsive and I don't know the exact value of it?
1 answer
0 points
You can set the left
and right
offset value to 0
and use auto
margins for both sides. Additionally, you will need to set the element's width
to a specific value.
Quick solution:
xxxxxxxxxx
1
.element {
2
position: absolute;
3
left: 0;
4
right: 0;
5
margin-left: auto;
6
margin-right: auto;
7
width: 150px; /* <----- specific value required */
8
}
Practical example
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.container {
7
height: 100px;
8
border: 1px solid lightgray;
9
}
10
11
.element {
12
position: absolute;
13
left: 0;
14
right: 0;
15
margin-left: auto;
16
margin-right: auto;
17
width: 150px; /* <----- specific value required */
18
}
19
20
</style>
21
</head>
22
<body>
23
<body>
24
<div class="container">
25
<div class="element">
26
Some text here...
27
</div>
28
</div>
29
</body>
30
</body>
31
</html>
0 commentsShow commentsAdd comment