初期マージン付き左寄せだが内部要素が膨らむとマージンを侵食して全幅になれるCSS

 last update 2024年3月14日

忘れそうなので自分用メモ。

内部要素(この例では img タグ)が十分に小さい場合は左右に margin(この例では figure::before , figure::after)を取りつつ内部要素を左寄せ。そして内部要素が margin を侵食するほど大きい場合は margin が左右等幅で elastic に縮小し、最大時は全幅まで広がる CSS 案。

<html>
    <head>
        <style>
          figure {
            display: flex;
            justify-content: start;
            width: 100%;
            margin: 0;
          }
          
          figure img {
            max-height: 640px; /* Not mandatory. Note for myself */
            max-width: 100%; /* Maximum width 100% (relative to the parent element) */
            flex-shrink: 0;
          }
          
          figure::before,
          figure::after {
            content: '';
            flex-shrink: 1;
            flex-basis: 10%; /* Set an elastic 10% margin with pseudo-elements */
            min-width: 0; /* Set the minimum width of pseudo-elements to 0 (allowing them to completely disappear if necessary)  */
          }
        </style>          
    </head>
    <body>
        <figure>
            <img src="Elastic_Image.JPG" alt="Description of the image">
        </figure>
    </body>
</html>
Code language: HTML, XML (xml)

上記例では、flex-basis で指定している10%が左右それぞれの初期マージンとして機能する。

Chrome でしかテストしてないので、全ての環境でちゃんと動くかは不明。

いずれ AI がプロンプトだけで書いてくれるようになると良いのだけども、現状ではちょっと無理だったので。色々祈念しつつわざと見える所に置いておく。

Hatena Pocket Line

コメントを記入