psb_david_petty
psb_david_petty

Reputation: 11

How to vertically center an iframe src in larger iframe with only CSS?

How do I vertically align the iframe src when it is shorter than the iframe itself — ideally only using CSS, but JS if necessary?

I have added code to a CodePen and pasted (a single-page version) below. The goal is to center the (1000x1000) purple square (src)in the (1100x1100) red border (iframe).

(Please have patience with my posting etiquette if I inadvertently overstep, as I rarely post.)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Test&hellip;</title>
<style>
/* Styles for this page... */
body {
  margin: 1%; padding: 1%;
  display: flex; flex-direction: column; justify-content: center; align-items: center;
  border: thin solid blue;
}
main {
  /* Like Google sites window. */
  width: 1175px; height: 1175px;
  display: flex; justify-content: center;  align-items: center;
  border: thin solid green;
}
footer { text-align: center; font-size: x-small; }

/* Styles for included code... */
div {
  overflow: hidden;
}
iframe {
  /* Flex Box style does nothing for the iframe src. */
  display: flex; flex-direction: column; justify-content: center; align-items: center;
  min-width: 1100px; min-height: 1100px;
  border: thin solid red;
}
</style>
</head>

<body>
  <main>
    <!-- HOW TO VERTICAL-ALIGN CENTER THE IFRAME SRC IN THE IFRAME? -->
    <div>
      <iframe src="https://psb-david-petty.github.io/p5js/2023-2024-bhs-schedule/whatever.html"></iframe>
    </div>
  </main>
  <footer>
    <!-- Explanatory footer... -->
    <p>
      <code>&lt;body&gt;</code> <span style="color: blue;">blue</span> border &mdash; 
      <code>&lt;main&gt;</code> 1175x1175 (like a <a href="https://sites.google.com/">Google sites</a> embed) <span style="color: green;">green</span> border &mdash; 
      <code>&lt;iframe&gt;</code> 1100x1100 <span style="color: red;">red</span> border
    </p>
  </footer>
</body>
</html>

I have searched on stackoverflow for solutions and tried several (flex box, display: table;, position: relative, responsive iframes, etc.). None seem to work.

I was expecting there to be a way to vertically center the src of an iframe in the iframe container.

EDIT: Clarified title. Fixed 1100x1100 dimension.

Upvotes: 1

Views: 66

Answers (0)

Related Questions