Sobes.tech
Middle

There are two nested blocks A and B with specified sizes. How to position block B exactly at the center of block A? Offer several options, including solutions for older browsers without flexbox support.

sobes.tech AI

Answer from AI

To center a nested block B exactly within block A, several approaches can be used:

1. Flexbox (modern method)

.parent {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;    /* vertical */
  width: 300px;  /* example */
  height: 200px; /* example */
}
.child {
  width: 100px;
  height: 50px;
}

2. Absolute positioning with transformation

.parent {
  position: relative;
  width: 300px;
  height: 200px;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100px;
  height: 50px;
}

3. Table alignment (for older browsers)

.parent {
  display: table;
  width: 300px;
  height: 200px;
  text-align: center;
}
.child {
  display: table-cell;
  vertical-align: middle;
  width: 100px;
  height: 50px;
  margin: 0 auto;
}

4. Using line-height (if the block height is fixed and contains text)

.parent {
  width: 300px;
  height: 200px;
  line-height: 200px; /* equal to parent's height */
  text-align: center;
}
.child {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
  width: 100px;
  height: 50px;
}

5. Using margin auto (only horizontally)

.child {
  width: 100px;
  height: 50px;
  margin: auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

For older browsers without flexbox support, it's better to use absolute positioning with transform or table alignment. Flexbox is the simplest and most versatile method for modern browsers.

There are two nested blocks A and B with specified… - sobes.tech