Buntstiftmuffin
Buntstiftmuffin

Reputation: 111

Using calc() on repsonsive width to center element

Is it possible to use calc() to center an element, which has a width defined with % ?

e.g.

.wrapper {
  width: 100%;
  background-color: black;
  height: 300px;
  position: absolute;
  top: 0;
}
.inside {
  width: 100%;
  margin-left: 30px;
  background-color: yellow;
  height: 250px;
  margin: 20px;
}
.inside h1 {
  width: 30%;
  background-color: white;
  text-align: center;
}
.inside h1 {
  position: absolute;
  left: calc(50% - 15%);
  left: -webkit-calc(50% - 15%);
}
<div class="wrapper">
  <div class="inside">
    <h1>CENTERED to viewport</h1>
  </div>
</div>

slider

This is the slider. It has a "string", which guides through the steps of the slider and the header is always in the middle of the screen. But for design purpose, the line starts a bit to the right and ends a bit to the left, which is given with a width of 80%. The top is slider no.1 with the string, the second slider, which is synced is the area with the big white square.

Maybe now it is a bit more clear, why I tried what I tried.

Upvotes: 3

Views: 29725

Answers (2)

HudsonPH
HudsonPH

Reputation: 1878

Yes, if you create a variable in the css for example:

<!DOCTYPE html>
<html>
<head>
<style>
#div1 {
    --Example: 200px;
    position: absolute;
    left: 50px;
    width: calc(100% - var(--Example)/2);
    border: 1px solid black;
    background-color: yellow;
    padding: 5px;
    text-align: center;
}
</style>
</head>
<body>

<div id="div1">Some text...</div>

</body>
</html>

Upvotes: 5

Pugazh
Pugazh

Reputation: 9561

If you can have fixed width just add margin: 0px auto. This will center the text horizontally.

.wrapper {
  width: 100%;
  background-color: black;
  height: 300px;
  position: absolute;
  top: 0;
}
.inside {
  margin-left: 30px;
  background-color: yellow;
  height: 250px;
  margin: 20px;
}
.inside h1 {
  width: 40%;
  background-color: white;
  text-align: center;
  margin: 0px auto;
}
<div class="wrapper">
  <div class="inside">
    <h1>CENTERED to viewport</h1>
  </div>
</div>

Upvotes: 0

Related Questions